题目链接:https://codeforc.es/contest/1283/problem/C
There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value fi is known: it is either fi=0 if the i-th friend doesn’t know whom he wants to give the gift to or 1≤fi≤n if the i-th friend wants to give the gift to the friend fi.
You want to fill in the unknown values (fi=0) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn’t contradictory.
If there are several answers, you can print any.
Input
The first line of the input contains one integer n (2≤n≤2⋅105) — the number of friends.
The second line of the input contains n integers f1,f2,…,fn (0≤fi≤n, fi≠i, all fi≠0 are distinct), where fi is the either fi=0 if the i-th friend doesn’t know whom he wants to give the gift to or 1≤fi≤n if the i-th friend wants to give the gift to the friend fi. It is also guaranteed that there is at least two values fi=0.
Output
Print n integers nf1,nf2,…,nfn, where nfi should be equal to fi if fi≠0 or the number of friend whom the i-th friend wants to give the gift to. All values nfi should be distinct, nfi cannot be equal to i. Each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself.
If there are several answers, you can print any.
Examples
input
5
5 0 0 2 4
output
5 3 1 2 4
input
7
7 0 0 1 4 0 6
output
7 3 2 1 4 5 6
input
7
7 4 0 3 0 5 1
output
7 4 2 3 6 5 1
input
5
2 1 0 0 0
output
2 1 4 5 3
题意
有 n 个人,第 i 个人打算把礼物给 fi ,fi = 0 表示第 i 个人还没想好给谁,要求输出一种给礼物的方案,使得每个人都收到一份礼物,并且送出一份礼物(不能送给自己)。
分析
经分析后我们发现,最后就是要将 1~n 个数放在 n 个位置上,x 不能放在 x 号位置(问题就是只在 0 号位置放)。
用队列的话会出现最后一个元素 x 刚好要放在 x 号位置上的情况,这样只需要和另外任意一个 0 号位置上已经放过的元素换个位置就行了。
代码
#include<bits/stdc++.h>
using namespace std;
int n;
queue<int> q;
int a[200007];
int vis[200007];
int zero[200007];
int cnt;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i] != 0) vis[a[i]] = 1;
}
for(int i=n;i>=1;i--)
if(vis[i] == 0) q.push(i);
for(int i=1;i<=n;i++)
{
if(a[i] == 0)
{
zero[++cnt] = i;
while(!q.empty())
{
int now = q.front();
q.pop();
if(now == i)
{
if(q.size() == 0)
{
a[i] = a[zero[1]];
a[zero[1]] = now;
break;
}
q.push(now);
continue;
}
a[i] = now;
break;
}
}
}
for(int i=1;i<=n;i++) printf("%d ",a[i]);
return 0;
}