This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
/*
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using ordered_set = tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>;
*/
#define all(x) begin(x), end(x)
#define sz(x) (int)x.size()
using ll = long long;
const int mod = 1e9+7;
void solve(int tc) {
int n, k;
cin >> n >> k;
vector<int> v(n);
for (auto &x : v) cin >> x;
map<vector<int>, bool> vis;
map<vector<int>, int> dist;
map<int, int> mp;
vector<array<int, 2>> ind(n);
for (int i = 0; i < n; ++i) {
mp[v[i]] = i;
ind[i][0] = v[i];
ind[i][1] = i;
}
sort(all(ind));
vector<unordered_set<int>> pos(n);
//pos[index] is set of positions where v[index] can be
for (int i = 0; i < n; i+=k) {
for (int j = i; j < i+k; ++j) {
for (int l = i; l < i+k; ++l) {
pos[ind[j][1]].insert(l);
}
}
}
vis[v] = true;
queue<vector<int>> q;
q.push(v);
bool can = true;
for (int i = 0; i < n; ++i) {
//start
int index = mp[v[i]];
if (!pos[index].count(i)) {
can = false;
break;
}
}
if (can) {
cout << dist[v] << '\n';
return;
}
while (!q.empty()) {
auto cur = q.front();
q.pop();
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= n; ++j) {
if (i != j and i+1 != j) {
vector<int> nv(n);
for (int l = 0; l < min(i, j); ++l) nv[l] = cur[l];
if (i < j) {
for (int l = j; l < n; ++l) nv[l] = cur[l];
for (int l = i; l < j-1; ++l) nv[l] = cur[l+1];
nv[j-1] = cur[i];
} else {
for (int l = i+1; l < n; ++l) nv[l] = cur[l];
nv[j] = cur[i];
for (int l = j+1; l < i+1; ++l) nv[l] = cur[l-1];
}
if (!vis[nv]) {
vis[nv] = true;
dist[nv] = dist[cur] + 1;
q.push(nv);
bool can = true;
for (int i = 0; i < n; ++i) {
//start
int index = mp[nv[i]];
if (!pos[index].count(i)) {
can = false;
break;
}
}
if (can) {
cout << dist[nv] << '\n';
return;
}
}
}
}
}
}
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int tc = 1;
//cin >> tc;
for (int i = 1; i <= tc; ++i) solve(i);
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |