2011: Permutation
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 5s | 8192K | 749 | 218 | Standard |
There are a group of strange people live in a strange island, where every morning each people gives his shoes(the unique) to his best friend(also the unique). Different people have different best friends. After a certain amount of days, they finally find that all the shoes come to their original owners. But they forget how many days have passed, so they ask Mr. Jojer, the most clever programmer, to find the least possible number of days.
Input and Output
The input may contain several test cases. Each test case contains an integer N(<30000) indicating the number of people(numbered by 1,2,…N) lived in the island. The following line of each test case contains N integers(range from 1 to N), the i th of which indicates the best friend of the person who is numbered by i.For each test case, you should print the least possible number of days in a single line.
Sample Input
2 2 1
Sample Output
2
#include<stdio.h>
int gcd(int x,int y)
{
if(y==0) return x;
return gcd(y,x%y);
}
int main()
{
int f[30000];
int n,i,j;
while(scanf("%d",&n)==1)
{
int b[30000]={0},t=1;
for(i=1;i<=n;i++) scanf("%d",&f[i]);
for(i=1;i<=n;i++)
{
if(b[i]==0)
{
int ci=0;j=i;
while(b[j]==0)
{
ci++;
b[j]=1;
b[j]=1;
j=f[j];
}
t=t*ci/gcd(t,ci);
}
}
printf("%d/n",t);
}
return 0;
}