Friends and Gifts

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
题意:每个人给另一个人礼物,要求每个人都分配到礼物,并且礼物来源不能来自自己。
思路:首先把没有送过礼的人的编号存起来,然后设置一个下标sta,用于记录上一个没有送过礼的人的下标,后面只需要当礼物分配时发现了自己送自己的情况,只需要和前面的互换礼物就可以了(因为一个人只和一个礼物冲突,礼物也是如此,所以换过去和换过来的不会出现自己送自己的情况),需要再对第一个自己送自己,第二个合法的情况特判一下.

#include"cstdio"
#include"cmath"
#include"cstring"
#include"algorithm"
using namespace std;
#define Maxn 200005
int x[Maxn],a[Maxn],b[Maxn],c[Maxn];
int main()
{
		int n;
		scanf("%d",&n);
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			b[a[i]]=1;
		}
		int t=0;
		for(int i=1;i<=n;i++)
		{
			if(b[i]==0)
			{
				c[t++]=i;
			}
		}
		int m=0,k=0,j=0;
		for(int i=1;i<=n;i++)
		{
			if(a[i]==0&&c[m]==i)
			{
				if(k==0)
				{
					j=1;
					k=i;
					a[i]=i;
				}
				else
				{
					a[i]=a[k];
					a[k]=c[m];
					k=i;
				}
				m++;
			}
			else if(a[i]==0&&c[m]!=i)
			{
				if(m==1&&j==1)
				{
					a[i]=a[k];
					a[k]=c[m];
					k=i;
					m++;
				}
				else
				{
					a[i]=c[m];
					k=i;
					m++;
				}
			}
		}
		for(int i=1;i<=n;i++)
		{
			if(i==1)
			{
				printf("%d",a[i]);
			}
			else
			{
				printf(" %d",a[i]);
			}
		}
		printf("\n");
	
	return 0;
 } 
发布了76 篇原创文章 · 获赞 1 · 访问量 2760

猜你喜欢

转载自blog.csdn.net/weixin_44824383/article/details/104919138