[POJ 2369]Permutations

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: 
 
This record defines a permutation P as follows: P(1) = 4, P(2) = 1, P(3) = 5, etc. 
What is the value of the expression P(P(1))? It’s clear, that P(P(1)) = P(4) = 2. And P(P(3)) = P(5) = 3. One can easily see that if P(n) is a permutation then P(P(n)) is a permutation as well. In our example (believe us) 
 
It is natural to denote this permutation by P2(n) = P(P(n)). In a general form the defenition is as follows: P(n) = P1(n), Pk(n) = P(Pk-1(n)). Among the permutations there is a very important one — that moves nothing: 
 
It is clear that for every k the following relation is satisfied: (EN)k = EN. The following less trivial statement is correct (we won't prove it here, you may prove it yourself incidentally): Let P(n) be some permutation of an N elements set. Then there exists a natural number k, that Pk = EN. The least natural k such that Pk = EN is called an order of the permutation P. 
The problem that your program should solve is formulated now in a very simple manner: "Given a permutation find its order."

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

题目大意:

给你n个点的置换,问你循环长度是多少。

题解:

置换入门题,分别求出每一个循环的大小,再求lcm即可。

 1 //Never forget why you start
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cstdlib>
 5 #include<cstring>
 6 #include<cmath>
 7 #include<algorithm>
 8 using namespace std;
 9 int n,a[1005],ans[1005],cnt,vis[1005];
10 int dfs(int r,int d){
11   if(vis[r])return d;
12   else{
13     vis[r]=1;
14     return dfs(a[r],d+1);
15   }
16 }
17 int gcd(int a,int b){
18   if(b==0)return a;
19   else return gcd(b,a%b);
20 }
21 int lcm(int a,int b){
22   return a*b/gcd(a,b);
23 }
24 int main(){
25   int i,j;
26   scanf("%d",&n);
27   for(i=1;i<=n;i++)scanf("%d",&a[i]);
28   for(i=1;i<=n;i++)
29     if(!vis[i])
30       ans[++cnt]=dfs(i,0);
31   for(i=cnt-1;i>=1;i--)
32     ans[i]=lcm(ans[i],ans[i+1]);
33   printf("%d\n",ans[1]);
34   return 0;
35 }

 

 

posted @ 2018-01-23 21:52  kakakakakaka  阅读(203)  评论(0编辑  收藏  举报

Never forget why you start

//鼠标爆炸特效