AtCoder Beginner Contest 178 F题解

Topic link

Problem Statement

Given are two sequences A and B, both of length N. A and B are each sorted in the ascending order. Check if it is possible to reorder the terms of B so that for each i (1≤i≤N) Ai≠Bi holds, and if it is possible, output any of the reorderings that achieve it.
————————————————
Input
Input is given from Standard Input in the following format:
N
A1 A2 ⋯ AN
B1 B2 ⋯ BN
————————————————
Output
If there exist no reorderings that satisfy the condition, print ‘No’.
If there exists a reordering that satisfies the condition, print ‘Yes’ on the first line. After that, print a reordering of B on the second line, separating terms with a whitespace.
If there are multiple reorderings that satisfy the condition, you can print any of them.
————————————————
Sample Input 1
6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1
Yes
2 2 3 1 1 1
————————————————
Sample Input 2
3
1 1 2
1 1 3

Sample Output 2
No

Title

Given two arrays of A and B that have been arranged from small to large, whether B can be arbitrarily replaced so that Ai is not equal to Bi for any i.

Ideas

Now that it has been sorted from small to large, first invert the B array, and then traverse from front to back. If the same is found, look for whether there is a number in the B array that can be exchanged with this bit to make two different numbers exist. Exchange, otherwise, the result does not exist.

Code

#include<map>
#include<stack>
#include<queue>
#include<string>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
int n,ans,res,sit,a[maxn],b[maxn];
int main()
{
    
    
	//ios::sync_with_stdio(false);
    //cin.tie(0);cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++)
    	cin>>a[i];
    for(int i=n;i>=1;i--)
		cin>>b[i];
	for(int i=1;i<=n;i++)
	{
    
    
		if(a[i]==b[i])
		{
    
    
			bool flag=0;
			for(int j=1;j<=n;j++)
			{
    
    
				if(a[i]!=b[j]&&a[j]!=b[i])
				{
    
    
					swap(b[i],b[j]);
					flag=1;
					break;
				}
			}
			if(!flag)
			{
    
    
				cout<<"No"<<endl;
				return 0;
			}
		}
	}
	cout<<"Yes"<<endl;
	for(int i=1;i<=n;i++)
		cout<<b[i]<<" ";
	cout<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/WTMDNM_/article/details/108598446