Description
We remind that the permutation of some final set is a one-to-one mapping of the set onto itself. Less formally, that is a way to reorder elements of the set. For example, one can define a permutation of the set {1,2,3,4,5} as follows:Input
In the first line of the standard input an only natural number N (1 <= N <= 1000) is contained, that is a number of elements in the set that is rearranged by this permutation. In the second line there are N natural numbers of the range from 1 up to N, separated by a space, that define a permutation — the numbers P(1), P(2),…, P(N).Output
You should write an only natural number to the standard output, that is an order of the permutation. You may consider that an answer shouldn't exceed 109.Sample Input
5 4 1 5 2 3
Sample Output
6
Source
Ural State University Internal Contest October'2000 Junior Session
題目要求為給定一個排列 4 1 5 2 3,問經過多少次置換可以重新回到這個排列。
定理:
什麼是循環節。。比如
1 2 3 4 5 從上向下看
4 1 5 2 31->4->2->1 (1,4,2)為一個循環節,長度為3 3->5->3(3,5)為一個循環節,長度為2 則所求的次數即定理中的k
下面的樣例解釋轉於博客 http://blog.csdn.net/cqlf__/article/details/7910849
#include#include using namespace std; int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int lcm(int a,int b)//求最小公倍數 { return a/gcd(a,b)*b; } const int maxn=1005; int num[maxn]; int visit[maxn]; int main() { int n; while(cin>>n) { for(int i=1;i<=n;i++) cin>>num[i]; memset(visit,0,sizeof(visit)); int res=1,flag; for(int i=1;i<=n;i++) { int count=0;//用來記錄每個循環節的長度 flag=i;//記錄下標 while(!visit[flag])//沒有被訪問過,不存在於之前的循環節中 { count++; visit[flag]=1; flag=num[flag]; } if(count)//注意有可能count是0的情況,即外層循環循環到第i個數,而此時第i個數在之前尋找循環節中已經被訪問過 res=lcm(count,res); } cout<