UVa 10570 - Meeting with Aliens(构造法)

将序列储存两遍,用数组代替环,然后枚举起点,每次都把当前数交换过来,即可得到答案。

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
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxn = 1010;
const int inf = 0x3f3f3f3f;
int a[maxn], b[maxn];

int main() {
int n;
while(~scanf("%d", &n) && n) {
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]), a[n + i] = a[i];
int ans = inf, cur = 0;
for(int i = 1; i <= n; ++i) {
memcpy(b, a, sizeof(a));
cur = 0;
for(int j = 1; j <= n && cur < ans; ++j) {
int k = i + j - 1;
if(b[k] != j) {
++cur;
int pos = k + 1;
while(pos < i + n) {
if(b[pos] == j) {swap(b[k], b[pos]); break;}
++pos;
}
}
}
ans = min(ans, cur);
memcpy(b, a, sizeof(a));
cur = 0;
for(int j = n; j >= 1 && cur < ans; --j) {
int k = i + n - j;
if(b[k] != j) {
++cur;
int pos = k + 1;
while(pos < i + n){
if(b[pos] == j) {swap(b[k], b[pos]); break;}
++pos;
}
}
}
ans = min(ans, cur);
}
printf("%d\n", ans);
}
return 0;
}

** 本文迁移自我的CSDN博客,格式可能有所偏差。 **