codefroces 612E Square Root of Permutation
A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1].
This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them.
The first line contains integer n (1 ≤ n ≤ 106) — the number of elements in permutation p.
The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of permutation p.
If there is no permutation q such that q2 = p print the number "-1".
If the answer exists print it. The only line should contain n different integers qi (1 ≤ qi ≤ n) — the elements of the permutation q. If there are several solutions print any of them.
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 #include<vector> 7 using namespace std; 8 struct ZYYS 9 { 10 int sum; 11 vector<int>p; 12 }s[1000001]; 13 int vis[1000001],tot,a[1000001],n,q[1000001],ans[1000001]; 14 bool cmp(ZYYS a,ZYYS b) 15 { 16 return a.sum<b.sum; 17 } 18 int gi() 19 { 20 char ch=getchar(); 21 int x=0; 22 while (ch<'0'||ch>'9') ch=getchar(); 23 while (ch>='0'&&ch<='9') 24 { 25 x=x*10+ch-'0'; 26 ch=getchar(); 27 } 28 return x; 29 } 30 int dfs(int x,int cnt) 31 { 32 if (vis[x]) return cnt; 33 vis[x]=1; 34 s[tot].p.push_back(x); 35 dfs(a[x],cnt+1); 36 } 37 int main() 38 {int i,flag=0,j; 39 cin>>n; 40 for (i=1;i<=n;i++) 41 a[i]=gi(); 42 for (i=1;i<=n;i++) 43 if (vis[i]==0) 44 { 45 s[++tot].sum=dfs(i,0); 46 } 47 sort(s+1,s+tot+1,cmp); 48 for (i=1;i<=tot;i++) 49 { 50 if (s[i].sum&1) continue; 51 else 52 { 53 if (s[i+1].sum==s[i].sum) {i++;continue;} 54 else {flag=1;break;} 55 } 56 } 57 if (flag) 58 { 59 cout<<-1<<endl; 60 return 0; 61 } 62 for (i=1;i<=tot;i++) 63 { 64 if (s[i].sum&1) 65 { 66 for (j=0;j<s[i].sum;j++) 67 { 68 q[(2*j)%s[i].sum]=s[i].p[j]; 69 } 70 for (j=0;j<s[i].sum;j++) 71 ans[q[j]]=q[(j+1)%s[i].sum]; 72 } 73 else 74 { 75 for (j=0;j<s[i].sum;j++) 76 { 77 ans[s[i].p[j]]=s[i+1].p[j]; 78 ans[s[i+1].p[j]]=s[i].p[(j+1)%s[i].sum]; 79 } 80 i++; 81 } 82 } 83 for (i=1;i<=n;i++) 84 printf("%d ",ans[i]); 85 }