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.
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.
The first line contains an integer n (1 ≤ n ≤ 105).
The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n).
If there is no answer, print one integer -1.
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 printm numbers h(1), ..., h(m).
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.
3 1 2 3
3 1 2 3 1 2 3
3 2 2 2
1 1 1 1 2
2 2 1
-1
前天的cf了,结果昨天vj上有场比赛,也没有补这个题,今天补上;
看的卿学姐的博客,然后又从网上看了篇博客才懂。。。我差不多已经是个废C~K了
主要还是数学思想吧,算是一个置换的水题吧。
题目中给出你两个公式,g(h(x))==x,h(g(x))==f(x);现给你f(x),让你求符合条件的g序列和h序列。
现在我们来把这两个式子变一下形。
我们知h(g(x))==f(x);
又知g(h(x))==x;
所以h(g(h(x)))==f(h(x)) ——>h(x)=f(h(x));
所以X==f(X)//整体代换
所以f(X)==f(f(X));
这个是用来判断是否能够构成序列的条件。
下面这一段话来自于大牛:http://www.cnblogs.com/zzuli2sjy/p/6400877.html
由h(g(x)) = f(x),假设f(x1) = f(x2);
那么有h(g(x1)) = h(g(x2)),那么我们假设g(x1)!=g(x2),那么就有h中存在两个相等的数,那么g(h(g(x1))) = g(x1),g(h(g(x2))) = g(x2)
就有个g(x1) = g(x2)所以假设不成立,那么h中的数都是不一样的,那么就为f中的不同种类数,m就确定了。
于是确定h(x),那么h(x)有许多的排列,假设x1,x2,h(x1) = a,h(x2) = b,f(y1) = a,f(y2) = b;
通过条件1求出g,h(g(a)) = f(a),h(g(b)) = f(b);-> g(a) = x1,g(b) = x2,那么有h(x1) = f(a),h(x2) = f(b);
那么假设h(x1) = b,h(x2) = a,可以推得g(a) = x2,g(b) = x1,有h(x2) = f(a),h(x1) = f(b),总是可以的f(a)= a,f(b) = b;
大牛的证法很详细,由此我们可以得出h序列其实就是f序列的去重序列,然后我们由h(g(x))==f(x)这个公式就可以推出来g序列了。
附上卿学姐的链接:http://www.cnblogs.com/qscqesze/p/6401529.html
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
using namespace std;
int a[200000];
int b[200000];
int c[200000];
map<int ,int>H;
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=1;i<=n;i++){
if(a[i]!=a[a[i]]){
return 0*printf("-1\n");
}
}
int m=0;
for(int i=1;i<=n;i++){
if(!H[a[i]]){
m++;
H[a[i]]=m;
c[m]=a[i];
}
b[i]=H[a[i]];
}
cout<<m<<endl;
for(int i=1;i<=n;i++){
printf(i==1?"%d":" %d",b[i]);
}
cout<<endl;
for(int i=1;i<=m;i++){
printf(i==1?"%d":" %d",c[i]);
}
cout<<endl;
return 0;
}