Problem Description
All bandits are afraid of Sheriff. Sheriff constantly fights crime, but when bandits lay low, he gets bored and starts to entertain himself.
This time Sheriff gathered all the bandits in his garden and ordered them to line up. After the whistle all bandits should change the order in which they stand.
Sheriff gave all the bandits numbers from 1 to N. For each place i he determined the unique position j. After whistling the bandit staying on position i should run to the j-th position. Sheriff loved seeing how the bandits move around, and he continued whistling until the evening. He finished the game only when he noticed that the bandits are in the same order in which they were standing originally.
Now the Sheriff asks the question: How many times has he whistled?
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.The first line of each test case contains a single integer N denoting the number of bandits. The second line contains N space-separated integers A1, A2, ..., AN denoting that the bandit staying on position i should run to the Ai-th position after the whistle.
Output
For each test case, output a single line containing number of times the sheriff had to whistle, print it modulo 10^9 + 7.Constraints
1 ≤ T ≤ 51 ≤ N ≤ 100000
All Ai are distinct numbers from 1 to N
Example
Input:
23
1 2 3
5
2 3 1 5 4
Output:
16
Explanation
Example case 2.the bandits positions are:
0. 1 2 3 4 5
1. 3 1 2 5 4
2. 2 3 1 4 5
3. 1 2 3 5 4
4. 3 1 2 4 5
5. 2 3 1 5 4
6. 1 2 3 4 5.
题解
题目不难,看意思大约是一定有解,所以一定存在若干个循环节。我们只要找出循环节,并求出lcm即可。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
#define ll long long
#define mod 1000000007
using namespace std;
int T,n,a[100002],pd[100002];
int num[100002],zz;
void init()
{
scanf("%d",&n);
int i;
for(i=1;i<=n;i++) scanf("%d",&a[i]);
}
int dfs(int x)
{
int i=a[x],ct=1;
pd[i]=1;
while(i!=x)
{i=a[i]; pd[i]=1; ct++;}
return ct;
}
int gcd(int x,int y)
{
if(y==0) return x;
else return gcd(y,x%y);
}
void pre()
{
memset(pd,0,sizeof(pd));
zz=0;
int i,t;
for(i=1;i<=n;i++)
{if(!pd[i])
num[++zz]=dfs(i);
}
}
void lcm()
{
ll ans=1;
int i,j;
for(i=1;i<=zz;i++)
{if(num[i]!=1)
{for(j=i+1;j<=zz;j++)
num[j]/=gcd(num[i],num[j]);
ans=(ans*num[i])%mod;
}
}
printf("%lld\n",ans);
}
int main()
{
scanf("%d",&T);
while(T--)
{init(); pre(); lcm();}
return 0;
}