http://blog.csdn.net/kksleric/article/details/7793397这篇文章或许可以看看
.
/* Problem ID: poj 2369 meaning: 求乱序到有序最少交换次数 Analyzing: 置换群 */ #include <iostream> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cstring> #include<vector> using namespace std; typedef struct even{int y1,y2,x;}even; #define FOR(i,s,t) for(int i=(s); i<(t); i++) #define LL long long #define BUG puts("here!!!") #define STOP system("pause") #define file_r(x) freopen(x, "r", stdin) #define file_w(x) freopen(x, "w", stdout) #define maxn 1006 LL gcd(LL a,LL b) {return a?gcd(b%a,a):b;} int main(){ int N; int A[maxn],vis[maxn]; scanf("%d",&N); FOR(i,0,N){ scanf("%d",&A[i]); A[i]=A[i]-1; } LL res=1,len; memset(vis,0,sizeof(vis)); FOR(i,0,N){ if(!vis[i]){ int j=i; len=0; while(!vis[j]){ len++; vis[j]=1; j=A[j]; } } res=res/gcd(res,len)*len; } printf("%d\n",res); return 0; }