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
inputCopy
5
5 0 0 2 4
outputCopy
5 3 1 2 4
inputCopy
7
7 0 0 1 4 0 6
outputCopy
7 3 2 1 4 5 6
inputCopy
7
7 4 0 3 0 5 1
outputCopy
7 4 2 3 6 5 1
inputCopy
5
2 1 0 0 0
outputCopy
2 1 4 5 3
题意:有n个人,每个人都会送出礼物,f[i]表示i送给谁了,现在有几个人没送,请你把这个空填上去。
解析:对于没送出的放到a数组,对于没收到的放到b数组。然后相互匹配,但是不能出现两两相同的
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10000;
map<int,int> v,mp;
vector<int> a,b;
int n,m;
int res[N];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>res[i];
v[res[i]]=1;
}
for(int i=1;i<=n;i++)
{
if(res[i]==0) a.push_back(i);
if(v[i]==0) b.push_back(i);
}
int k=0;
m=a.size();
for(int i=0;i<m;i++)
{
if(a[i]==b[i])
{
int x=i;
int y=(i+1)%m;
swap(b[x],b[y]);
}
}
for(int i=0;i<m;i++ ) res[a[i]]=b[i];
for(int i=1;i<=n;i++) cout<<res[i]<<" ";
cout<<endl;
}