首页 > 代码库 > Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) D. Artsem and Saunders
Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) D. Artsem and Saunders
地址:http://codeforces.com/contest/765/problem/D
题目:
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 print mnumbers 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
思路:这题思路清晰的人应该可以很快做出来的。
g(h(x))?=?x ,可以推出m<=n;
h(g(x))=f(x),可以推出m>=f(x)中不同元素的个数。
先保证第二个条件h(g(x))=f(x):
h[]=去重后的f[]。同时记录f[i]在h[]中的hash值:g[i]hash[f[i]]。
然后扫一遍g[h[i]],判断值是否为x。
我不知道怎么证明可以这么做,感觉可行后莽一发就ac了。
有谁知道了可以交流下。
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 #define MP make_pair
6 #define PB push_back
7 typedef long long LL;
8 typedef pair<int,int> PII;
9 const double eps=1e-8;
10 const double pi=acos(-1.0);
11 const int K=1e5+7;
12 const int mod=1e9+7;
13
14 int n,m,ans;
15 int h[K],g[K],f[K];
16 map<int,int>hs;
17
18 int main(void)
19 {
20 cin>>n;
21 for(int i=1,x;i<=n;i++)
22 {
23 scanf("%d",&x),f[i]=x;
24 if(!hs[x]) h[++m]=x,hs[x]=m;
25 }
26 for(int i=1;i<=n;i++)
27 g[i]=hs[f[i]];
28 for(int i=1;i<=m;i++)
29 if(g[h[i]]!=i) ans=1;
30 if(ans)
31 printf("-1\n");
32 else
33 {
34 printf("%d\n",m);
35 for(int i=1;i<=n;i++)
36 printf("%d ",g[i]);
37 puts("");
38 for(int i=1;i<=m;i++)
39 printf("%d ",h[i]);
40 puts("");
41 }
42 return 0;
43 }
Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) D. Artsem and Saunders