您的位置:首页 > 其它

UVa 10570 - Meeting with Aliens(构造法)

2015-07-25 19:18 344 查看
将序列储存两遍,用数组代替环,然后枚举起点,每次都把当前数交换过来,即可得到答案。

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: