题解:P17220 [ICPC 2017 Nanning R] Rearrangement
yusx142857 · · 题解
题解:P17220 [ICPC 2017 Nanning R] Rearrangement
题目传送门
题意
在一个大小为 2×n 的二维整数数组中,是否可能重新排列这些整数,使得任意两个相邻元素(指同一行或同一列中相邻的元素)之和永远不被 3 整除。
思路解析
我们思考一下,什么时候两个正整数的和能被3整除。
- 两个数模3的余数都是
0 (0 + 0 = 0) ; - 一个数模3的余数为
1 ,另一个为2 (1 + 2 = 3) ;
我们可以把余数为
那么我们需要分别统计一下余数为
画图思考一下,就可以发现规律:
- 当
cnt0 = 2n 或者cnt1 = 2n 或者cnt2 = 2n 时,任意两个相邻元素之和肯定不被 3 整除; - 保证
1 的情况下,当cnt0 > n 时肯定会有两个余数为0 的数相邻; - 保证
1 、2 的情况下,当cnt0 > 3 时肯定会有解; - 当
cnt0 = 2 时,如果cnt1 \bmod 2 = 0 肯定会有余数为0 、余数为1 的数相邻; - 当
cnt0 = 1 或者cnt0 = 0 时,如果cnt1 > 0 并且cnt2 > 0 肯定会有余数为0 、余数为1 的数相邻; - 剩下的就是YES的情况。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int cnt0=0,cnt1=0,cnt2=0;
for(int i=1;i<=2*n;i++){
int x;
cin>>x;
int mod=x%3;
if(mod==0)cnt0++;
else if(mod==1)cnt1++;
else cnt2++;
}
if(cnt0==2*n){
cout<<"NO\n";
continue;
}
if(cnt0>n){
cout<<"NO\n";
continue;
}
if(cnt0==0&&cnt1>=1&&cnt2>=1){
cout<<"NO\n";
}
else if(cnt0==1&&cnt1>=1&&cnt2>=1){
cout<<"NO\n";
}
else if(cnt0==2){
if(cnt1%2==0){
cout<<"NO\n";
}else{
cout<<"YES\n";
}
}
else{
cout<<"YES\n";
}
}
return 0;
}
管理员,求通过!