[CF 612E]Square Root of Permutation

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].node

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.ios

Input

The first line contains integer n (1 ≤ n ≤ 106) — the number of elements in permutation p.ide

The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of permutation p.spa

Output

If there is no permutation q such that q2 = p print the number "-1".code

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.blog

Examples

input

4
2 1 4 3

output

3 4 2 1

input

4
2 1 3 4

output

-1

input

5
2 3 4 5 1

output

4 5 1 2 3

題目大意:

給你個置換p,而後作平方運算,獲得置換q,題目給你q,問你可否找到p,要構造出來。ci

題解:

這道題要求倒推出一個置換,因爲原置換p中的環不必定全是奇數環,因此平方以後有可能有環會裂開。element

對於平方後的置換q中的奇數環,直接在裏面推。偶數環就看是否有相同大小的偶數環與它合併。get

 

 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 #include<vector>
 9 using namespace std;
10 int n,m,a[1000005],lm,ans[1000005],q[1000005];
11 struct node{
12   int sum;
13   vector<int>p;
14   friend bool operator < (const node a,const node b){
15     return a.sum<b.sum;
16   }
17 }s[1000005];
18 int vis[1000005],cnt;
19 void dfs(int r){
20   vis[r]=1;
21   cnt++;
22   s[lm].p.push_back(r);
23   if(vis[a[r]])return;
24   else dfs(a[r]);
25 }
26 int main(){
27   int i,j;
28   scanf("%d",&n);
29   for(i=1;i<=n;i++)scanf("%d",&a[i]);
30   for(i=1;i<=n;i++)
31     if(!vis[i]){
32       cnt=0;
33       lm++;
34       dfs(i);
35       s[lm].sum=cnt;
36     }
37   sort(s+1,s+lm+1);
38   bool flag=0;
39   for(i=1;i<=lm;i++){
40     if(s[i].sum&1)continue;
41     else{
42       if(s[i+1].sum==s[i].sum){i++;continue;}
43       else {flag=1;break;}
44     }
45   }
46   if(flag){printf("-1\n");return 0;}
47   for(i=1;i<=lm;i++){
48     if(s[i].sum&1){
49       for(j=0;j<s[i].sum;j++)
50     q[j*2%s[i].sum]=s[i].p[j];
51       for(j=0;j<s[i].sum-1;j++)
52     ans[q[j]]=q[j+1];
53       ans[q[s[i].sum-1]]=q[0];
54     }
55     else{
56       int k=i+1;
57       for(j=0;j<s[i].sum;j++){
58     ans[s[i].p[j]]=s[k].p[j];
59     ans[s[k].p[j]]=s[i].p[(j+1)%s[i].sum];
60       }
61       i++;
62     }
63   }
64   for(i=1;i<=n;i++)
65     printf("%d ",ans[i]);
66   return 0;
67 }
相關文章
相關標籤/搜索