-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem0180.h
83 lines (75 loc) · 2.28 KB
/
Problem0180.h
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// Created by Fengwei Zhang on 2021/7/27.
//
#ifndef ACWINGSOLUTION_PROBLEM0180_H
#define ACWINGSOLUTION_PROBLEM0180_H
#include <iostream>
#include <cstring>
using namespace std;
class Problem0180 {
// https://www.acwing.com/solution/content/4050/
private:
const int MAX_DEPTH = 5, N = 15;
int books[N];
int levelTemp[MAX_DEPTH][N];
int funcF(const int n) {
int tot = 0;
for (int i = 1; i < n; ++i) {
if (books[i] == books[i - 1] + 1) {
continue;
}
++tot;
}
return (tot + 2) / 3; // 返回tot/3(上取整)
}
bool dfs(const int currentDepth, const int n, const int maxDepth) {
if (currentDepth + funcF(n) > maxDepth) {
return false;
}
if (funcF(n) == 0) {
return true;
}
for (int length = 1; length <= n; ++length) { // 把长度为length的部分放到其他位置
for (int start = 0; start + length - 1 < n; ++start) {
int end = start + length - 1;
for (int k = end + 1; k < n; ++k) {
memcpy(levelTemp[currentDepth], books, n * sizeof(int));
int y = start;
for (int x = end + 1; x <= k; ++x, ++y) {
books[y] = levelTemp[currentDepth][x];
}
for (int x = start; x <= end; ++x, ++y) {
books[y] = levelTemp[currentDepth][x];
}
if (dfs(currentDepth + 1, n, maxDepth)) {
return true;
}
memcpy(books, levelTemp[currentDepth], n * sizeof(int));
}
}
}
return false;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &books[i]);
}
int d = 0;
while (d < 5 && !dfs(0, n, d)) {
++d;
}
if (d >= 5) {
printf("5 or more\n");
} else {
printf("%d\n", d);
}
}
return 0;
}
};
#endif //ACWINGSOLUTION_PROBLEM0180_H