UVA 10570 Meeting with Aliens

#include<bits/stdc++.h>
#define REP(i,a,b) for(int i=a;i<=b;i++)
#define MS0(a) memset(a,0,sizeof(a))

using namespace std;

typedef long long ll;
const int maxn=1000100;
const int INF=1<<29;

int n,a[maxn];
int a1[maxn],id1[maxn];
int a2[maxn],id2[maxn];

int solve(int m,int *a,int *id)
{
    if(m==0) return 0;
    if(a[m]==m) return solve(m-1,a,id);
    int x=id[m];
    swap(a[x],a[m]);
    swap(id[a[x]],id[a[m]]);
    return 1+solve(m-1,a,id);
}

int main()
{
    freopen("in.txt","r",stdin);
    while(cin>>n,n){
        MS0(id1);MS0(id2);
        int st=1;
        REP(i,1,n) scanf("%d",&a[i]);
        int ans=INF;
        REP(st,1,n){
            REP(i,st,n) a1[i-st+1]=a[i];
            REP(i,1,st-1) a1[i+(n-st+1)]=a[i];
            int t=0;
            for(int i=st;i>=1;i--) a2[++t]=a[i];
            for(int i=n;i>st;i--) a2[++t]=a[i];
            REP(i,1,n) id1[a1[i]]=i,id2[a2[i]]=i;
            //cout<<st<<" "<<ans<<endl;
            ans=min(ans,min(solve(n,a1,id1),solve(n,a2,id2)));
        }
        cout<<ans<<endl;
    }
    return 0;
}

/**
为何枚举起点就过了呢,这和直接取1为起点有何不同?
*/
View Code

 一开始直接以1为起点没过,而把起点枚举了一下却莫名其妙地过了,虽然不知道为什么,但是敢想敢做是acmer的必备素质。

 

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