#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; if(k == 0){ cout << 0 << '\n'; exit(0); } vector p(n), b(n), pre, cnt_p(n); ll ans = 0, tot = 0; for(auto &&v : p) cin >> v, v--; for(int i = 0; i < n; i++){ cin >> b[i]; tot += abs(p[i] - (--b[i])); } ans = tot; pre = p; k--; while(k--){ next_permutation(p.begin(), p.end()); bool flag = true; int cnt = 0, i = n - 1; for(; i >= 0 && (cnt >= 1 || flag); i--){ if(p[i] != pre[i]){ flag = false; cnt_p[p[i]]++; cnt_p[pre[i]]--; cnt += (cnt_p[p[i]] == 1 ? 1 : -1) + (cnt_p[pre[i]] == -1 ? 1 : -1); } tot += abs(p[i] - b[i]) - abs(pre[i] - b[i]); } ans += tot; for(int j = max(0, i); j < n; j++){ cnt_p[p[j]] = 0; pre[j] = p[j]; } } cout << ans << '\n'; }