結果
| 問題 |
No.270 next_permutation (1)
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-04-29 19:31:30 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 24 ms / 2,000 ms |
| コード長 | 1,089 bytes |
| コンパイル時間 | 1,698 ms |
| コンパイル使用メモリ | 171,432 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-11-18 13:11:24 |
| 合計ジャッジ時間 | 3,108 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 15 |
ソースコード
#include <bits/stdc++.h>
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<int> 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';
}