// yukicoder: No.270 next_permutation (1) // 2019.8.1 bal4u #include typedef long long ll; #if 1 #define gc() getchar_unlocked() #else #define gc() getchar() #endif int in() { // 非負整数の入力 int n = 0, c = gc(); // while (isspace(c)) c = gc(); do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0'); return n; } #define ABS(x) ((x)>=0?(x):-(x)) int p[100005]; int N; int b[100005]; ll sum; void swap(int i, int j) { int t; sum -= ABS(b[i]-p[i]) + ABS(b[j]-p[j]); t = p[i], p[i] = p[j], p[j] = t; sum += ABS(b[i]-p[i]) + ABS(b[j]-p[j]); } /* algorithm of next_permutation in lexicographic order Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. Find the largest index l greater than k such that a[k] < a[l]. Swap the value of a[k] with that of a[l]. Reverse the sequence from a[k + 1] up to and including the final element a[n]. */ void next_permutation(void) { int k, l, r; // 右端にある最も長い降順部分列 p[k+1]... p[N-1]をみつける k = N-2; while (k >= 0 && p[k] > p[k+1]) k--; // 上記の降順部分列を昇順列に戻す l = k+1, r = N-1; while (l < r) swap(l, r), l++, r--; if (k < 0) return; //p[k]より大きい要素 p[r]を見つけ、交換する r = k+1; while (p[k] > p[r]) r++; swap(r, k); } int main() { int i, K, f; ll ans; N = in(), K = in(); if (K == 0) { puts("0"); return 0; } for (i = 0; i < N; i++) p[i] = in(); sum = 0, f = 0; for (i = 0; i < N; i++) { b[i] = in(), sum += ABS(b[i]-p[i]); if (b[i] < N) f = 1; } if (f) { ans = 0; while (K--) ans += sum, next_permutation(); printf("%lld\n", ans); } else printf("%lld\n", sum*K); return 0; }