UVa #10570 Meeting with Aliens (习题8-13)

来源:互联网 发布:韵达快运网络招商 编辑:程序博客网 时间:2024/06/03 13:14

枚举开头的人的位置。每次将一个人放到正确的座位,正反过两次取最小,这样便是交换次数最少的方法。


需要留意的是,需要枚举开头的人,而不能固定某一个为开头。


Run Time: 0.245s

#define UVa  "8-13.10570.cpp"//Meeting with Aliens.char fileIn[30] = UVa, fileOut[30] = UVa;#include<cstring>#include<cstdio>#include<algorithm>using namespace std;//Global Variables. Reset upon Each Case!const int maxn = 500 + 10;int N, start;int data[maxn], p[maxn];int a[maxn], b[maxn];int pa[maxn], pb[maxn];/////int main() {    while(scanf("%d", &N) && N) {        int tmp;        for(int i = 0; i < N; i ++) {            scanf("%d", &tmp);            tmp --;            data[i] = tmp;            p[tmp] = i;        }        int ans = maxn;        for(start = 0; start < N; start ++) {            for(int i = 0; i < N; i ++) {                a[i] = b[i] = data[i];                pa[i] = pb[i] = p[i];            }            int cnt1 = 0, cnt2 = 0;            for(int i = 1; i < N; i ++) {                int u = (start + i)%N, offset = (u+N-start)%N;                if(a[u] != offset) {                    swap(a[u], a[pa[offset]]);                    swap(pa[a[u]], pa[a[pa[offset]]]);                    cnt1 ++;                }            }            for(int i = 1; i < N; i ++) {                int u = (start - i + N)%N, offset = (N-(u-start))%N;                if(b[u] != offset) {                    swap(b[u], b[pb[offset]]);                    swap(pb[b[u]], pb[b[pb[offset]]]);                    cnt2 ++;                }            }            ans = min(ans, min(cnt1, cnt2));        }        printf("%d\n", ans);    }    return 0;}

0 0