D. Artsem and Saunders
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard outputweb
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.数组
Let [n] denote the set {1, …, n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, …, x, and all its values are integers from 1 to y.svg
Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all , and h(g(x)) = f(x) for all , or determine that finding these is impossible.
Inputui
The first line contains an integer n (1 ≤ n ≤ 105).spa
The second line contains n space-separated integers — values f(1), …, f(n) (1 ≤ f(i) ≤ n).
Outputrest
If there is no answer, print one integer -1.code
Otherwise, on the first line print the number m (1 ≤ m ≤ 106). On the second line print n numbers g(1), …, g(n). On the third line print m numbers h(1), …, h(m).xml
If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.
Examples
Inputinput
3
1 2 3string
Output
3
1 2 3
1 2 3
Input
3
2 2 2
Output
1
1 1 1
2
Input
2
2 1
Output
-1
给出数组 a,是否能够构造出数组g,h知足 :g(h(x)) = x ,h(g(x)) = f(x)
数组h不重复记录数组a里的元素,数组g(x)记录a[x]在h数组里的位置,但若a[x] != x,便没法构成
AC代码:
#include<cstdio>
#include<algorithm>
using namespace std;
const int K = 1e5 + 10;
int a[K],b[K],c[K],ok[K];
int main()
{
int N;
scanf("%d",&N);
for(int i = 1; i <= N; i++) scanf("%d",&a[i]),ok[a[i]] = 1;
int nl = 0;
for(int i = K - 1; i >= 1; i--)
if(ok[i]){
c[++nl] = i,b[i] = nl;
if(a[i] != i){printf("-1\n"); return 0;}
}
printf("%d\n",nl);
for(int i = 1; i <= N; i++) printf("%d ",b[a[i]]);printf("\n");
for(int i = 1; i <= nl; i++) printf("%d ",c[i]);
return 0;
}