题意:给你一堆无序的数列p,求k,使得p^k=p
思路:利用置换的性质,先找出所有的循环,然后循环中元素的个数的lcm就是答案
代码:
#include <cstdio> #include <cstring> #include <iostream> #define maxn 1234 using namespace std; int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } int lcm(int a,int b) { return a*b/gcd(a,b); } int main(int argc, char const *argv[]) { int n; int data[maxn]; bool visit[maxn]; int ans; while(cin>>n) { for(int i=1;i<=n;i++) cin>>data[i]; ans=1; memset(visit,false,sizeof(visit)); for(int i=1;i<=n;i++) { if(!visit[i]) { int len=1; visit[i]=true; int tmp = data[i]; while(tmp!=i) { visit[tmp]=true; tmp=data[tmp]; len++; } ans=lcm(ans,len); } } cout<<ans<<endl; } return 0; }