Codeforces Round #611 (Div. 3) C题

在Codeforces Round #611 (Div. 3) 中,有n位朋友互相赠送新年礼物,每位朋友必须送出并收到一份礼物,且不能给自己送礼。题目描述了朋友间礼物交换的初始信息,并要求填充未知的礼物接收者,确保无矛盾。输入包含朋友数n和初始的礼物分配,至少有两个朋友未指定接收者。解决方案包括保存未出现的数字,针对0值的位置反向枚举,若仍有冲突则正向枚举,确保所有礼物交换有效且不自赠。
摘要由CSDN通过智能技术生成

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.


又被hack了,难受啊!!!

要改变0位置的 a[i] 不与该位置的 i 相等,我们可以保存没有出现的数字,保存值为 0 的位置,然后枚举位置 i ,当 a[i]==0 时,反向枚举没有出现的的数字;这里的反向枚举有可能还是有相等的可能,所以还要判断一下,如果还是有相等,就正向枚举,就这两种情况;

代码:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=200100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值