AtCoder Beginner Contest 178 F题解

题目链接

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

题意

给定两个已经从小到大排列的A,B数组,是否可以对B作任意调换使得对于任意的i,Ai不等于Bi。

思路

既然已经从小到大排序了,则首先将B数组倒置,然后从前向后遍历,若寻到相同的就寻找B数组中是否有可以与此位交换后使得两位都不同的数存在,若有则交换,无则说明结果不存在。

代码

#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;
}
AtCoder Beginner Contest 134 是一场 AtCoder 的入门级比赛,以下是每道题的简要题解: A - Dodecagon 题目描述:已知一个正十二边形的边长,求它的面积。 解题思路:正十二边形的内角为 $150^\circ$,因此可以将正十二边形拆分为 12 个等腰三角形,通过三角形面积公式计算面积即可。 B - Golden Apple 题目描述:有 $N$ 个苹果和 $D$ 个盘子,每个盘子最多可以装下 $2D+1$ 个苹果,求最少需要多少个盘子才能装下所有的苹果。 解题思路:每个盘子最多可以装下 $2D+1$ 个苹果,因此可以将苹果平均分配到每个盘子中,可以得到最少需要 $\lceil \frac{N}{2D+1} \rceil$ 个盘子。 C - Exception Handling 题目描述:给定一个长度为 $N$ 的整数序列 $a$,求除了第 $i$ 个数以外的最大值。 解题思路:可以使用两个变量 $m_1$ 和 $m_2$ 分别记录最大值和次大值。遍历整个序列,当当前数不是第 $i$ 个数时,更新最大值和次大值。因此,最后的结果应该是 $m_1$ 或 $m_2$ 中较小的一个。 D - Preparing Boxes 题目描述:有 $N$ 个盒子和 $M$ 个物品,第 $i$ 个盒子可以放入 $a_i$ 个物品,每个物品只能放在一个盒子中。现在需要将所有的物品放入盒子中,每次操作可以将一个盒子内的物品全部取出并分配到其他盒子中,求最少需要多少次操作才能完成任务。 解题思路:首先可以计算出所有盒子中物品的总数 $S$,然后判断是否存在一个盒子的物品数量大于 $\lceil \frac{S}{2} \rceil$,如果存在,则无法完成任务。否则,可以用贪心的思想,每次从物品数量最多的盒子中取出一个物品,放入物品数量最少的盒子中。因为每次操作都会使得物品数量最多的盒子的物品数量减少,而物品数量最少的盒子的物品数量不变或增加,因此这种贪心策略可以保证最少需要的操作次数最小。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值