找循环节求lcm就够了,若答案是12345应该输出1,被坑了下。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
#define INF 0x3FFFFFF
#define MAXN 2222
#define eps 1e-6
int a[MAXN],p[MAXN],b[MAXN],vis[MAXN];
int gcd(int a,int b) {return a%b==0?b:gcd(b,a%b);}
int lcm(int a,int b) {return a/gcd(a,b)*b;}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
{
a[i]=i;
vis[i]=0;
scanf("%d",&p[i]);
}
int ans=1;
for(int i=1;i<=n;i++)
{
if(vis[i]) continue;
int now=a[i];
int cnt=0;
while(1)
{
vis[now]=1;
now=p[now];
cnt++;
if(now==a[i]) break;
}
ans=lcm(ans,cnt);
}
printf("%d\n",ans);
}
return 0;
}