Codeforces Round #611 (Div. 3) C题

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
#define LL long long
#define pa pair
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=200100;
const int M=1000100;
const LL mod=998244353;
int a[200100];
bool vis[200100];
int b[200100];
int c[200100]; 
int n;
bool judge(){
     
	for(int i=1;i<=n;i++){
     
		if(i==c[i]) return false;
	}
	return true;
}
int main(){
     
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++){
     
		cin>>a[i];
		if(a[i]) vis[a[i]]=true;
	}
	int ans=0; 
	for(int i=n;i>=1;i--){
     
		if(!vis[i]){
     
			b[ans++]=i;
		}
	}
	sort(b,b+ans);
	int l=0,r=ans-1;
	for(int i=1;i<=n;i++){
     
		if(a[i]){
     
			c[i]=a[i];
		}
		else{
     
			if(i!=b[r]){
     
				c[i]=b[r];
				r--;
			}
			else{
     
				c[i]=b[l];
				l++;	
			}	
		}	
	}
	if(judge()){
     
		for(int i=1;i<=n;i++) cout<<c[i]<<" "; 
	}
	else{
     
		l=0;
		r=ans-1;
		for(int i=1;i<=n;i++){
     
			if(a[i]){
     
				cout<<a[i]<<" ";
			}
			else{
     
				if(i!=b[l]){
     
					cout<<b[l]<<" ";
					l++;
				}
				else{
     
					cout<<b[r]<<" ";
					r--;
				}	
			}	
		}
	}
	return 0;
}

你可能感兴趣的:(#,codeforces上分记录,#,思维,codeforces)