UVA 10570 Meeting with Aliens

题意:没想到怎么移动才能达到最小,参考了:点击打开链接
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int a[5555],b[555],n;
bool mark[555];

int calcu(int cur){
    int ans = 0;
    for (int i = 1; i <= n; i++)
        mark[i] = 0;
    for (int i = 1; i <= n; i++){
        if (b[i] == i || mark[i])
            continue;
        mark[i] = 1;
        int p = b[i];
        while (!mark[p]){
            mark[p] = 1;
            p = b[p];
            ans++;
        }
    }
    if (ans > cur)
        ans = cur;
    return ans;
}

int getans(int cur,int s){
    for (int i = 0; i < n; i++)
        b[i+1] = a[s+i];
    cur = calcu(cur);
    
    for (int i = 0; i < n; i++)
        b[i+1] = a[s+n-i];
    cur = calcu(cur);
    return cur;
}

int main(){
    while (scanf("%d",&n) != EOF && n){
        for (int i = 1; i <= n; i++)
            scanf("%d",&a[i]),a[i+n] = a[i];
        int ans = n,tmp;
        for (int i = 1; i <= n; i++){
            if (ans == 0)
                break;
            ans = getans(ans,i);
        }
        printf("%d\n",ans);
    }
    return 0;
}



你可能感兴趣的:(UVA 10570 Meeting with Aliens)