-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path28_SORTGAME.cpp
68 lines (61 loc) · 1.36 KB
/
28_SORTGAME.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <cstdio>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
// 코드 29.4 Sorting Game 문제를 빠르게 해결하는 너비 우선 탐색의 구현
map<vector<int>, int> toSort;
// [0, ..., n-1]의 모든 순열에 대해 toSort[]를 계산해 저장한다
void precalc(int n) {
vector<int> perm(n);
for (int i = 0; i < n; ++i)
perm[i] = i;
queue<vector<int> > q;
q.push(perm);
toSort[perm] = 0;
while (!q.empty()) {
vector<int> here = q.front();
q.pop();
int cost = toSort[here];
for (int i = 0; i < n; ++i) {
for (int j = i + 2; j <= n; ++j) {
reverse(here.begin() + i, here.begin() + j);
if (toSort.count(here) == 0) {
toSort[here] = cost + 1;
q.push(here);
}
reverse(here.begin() + i, here.begin() + j);
}
}
}
}
int solve(const vector<int>& perm) {
// perm을 [0, ..., n-1]의 순열로 변환한다
int n = perm.size();
vector<int> fixed(n);
for (int i = 0; i < n; ++i) {
int smaller = 0;
for (int j = 0; j < n; ++j) {
if (perm[j] < perm[i])
++smaller;
fixed[i] = smaller;
}
}
return toSort[fixed];
}
int main(void) {
int C, n;
scanf("%d", &C);
for (int i = 1; i <= 8; i++)
precalc(i);
while (C--) {
scanf("%d", &n);
vector<int> num(n, 0);
for (int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
printf("%d\n", solve(num));
}
return 0;
}