C. Friends and Gifts

链接:https://codeforces.com/contest/1283/problem/C

There are nn 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 fifi is known: it is either fi=0fi=0 if the ii-th friend doesn't know whom he wants to give the gift to or 1≤fi≤n1≤fi≤n if the ii-th friend wants to give the gift to the friend fifi.

You want to fill in the unknown values (fi=0fi=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 nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of friends.

The second line of the input contains nn integers f1,f2,…,fnf1,f2,…,fn (0≤fi≤n0≤fi≤n, fi≠ifi≠i, all fi≠0fi≠0 are distinct), where fifi is the either fi=0fi=0 if the ii-th friend doesn't know whom he wants to give the gift to or 1≤fi≤n1≤fi≤n if the ii-th friend wants to give the gift to the friend fifi. It is also guaranteed that there is at least two values fi=0fi=0.

Output

Print nn integers nf1,nf2,…,nfnnf1,nf2,…,nfn, where nfinfi should be equal to fifi if fi≠0fi≠0 or the number of friend whom the ii-th friend wants to give the gift to. All values nfinfi should be distinct, nfinfi cannot be equal to ii. 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

Copy

5
5 0 0 2 4

output

Copy

5 3 1 2 4 

input

Copy

7
7 0 0 1 4 0 6

output

Copy

7 3 2 1 4 5 6 

input

Copy

7
7 4 0 3 0 5 1

output

Copy

7 4 2 3 6 5 1 

input

Copy

5
2 1 0 0 0

output

Copy

2 1 4 5 3 

代码:

#include <bits/stdc++.h>
using namespace std;
long long t,n,a,b,k,s;
long long f[200001];
map<long long ,long long >m;
queue<long long>q,p; 
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    	cin>>f[i];
    	if(f[i]!=0)
    	{
    		m[f[i]]=1;
    	}
    	else
    	p.push(i);
    	
	}
    for(int i=1;i<=n;i++)
    {
    	if(m[i]==0)
    	q.push(i);
    }
    for(int i=1;i<=n;i++)
    {
    	if(f[i]==0)
    	{
    		a=q.front();
    		q.pop();
    		if(a==i)
    		{
    			q.push(a);
    			a=q.front();
    			q.pop();
    			if(a==i)
    			{
    				b=p.front();
    				p.pop();
    				if(b==i)
    				{
    					b=p.front();
    					p.pop();
    				}
    				f[i]=f[b];
    				f[b]=a;
    			}
    			else
    			f[i]=a;
    		}
    		else
    		f[i]=a;
    	}
    }
    for(int i=1;i<=n;i++)
    {
    	cout<<f[i]<<" ";
    }
}

 

全部评论

相关推荐

昨天 16:23
门头沟学院 Java
点赞 评论 收藏
分享
落媛媛:同学,瞅瞅我司,医疗独角兽,校招刚开,名额有限,先到先得,我的主页最新动态,绿灯直达,免笔试~
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务