题解:P17220 [ICPC 2017 Nanning R] Rearrangement

· · 题解

题解:P17220 [ICPC 2017 Nanning R] Rearrangement

题目传送门

题意

在一个大小为 2×n 的二维整数数组中,是否可能重新排列这些整数,使得任意两个相邻元素(指同一行或同一列中相邻的元素)之和永远不被 3 整除。

思路解析

我们思考一下,什么时候两个正整数的和能被3整除。

  1. 两个数模3的余数都是 0 (0 + 0 = 0);
  2. 一个数模3的余数为 1,另一个为 2 (1 + 2 = 3);

我们可以把余数为 0 的数作为屏障把余数为 1 和余数为 2 的数分隔开,如图:

那么我们需要分别统计一下余数为 0 、余数为 1 和余数为 2 的数量。

画图思考一下,就可以发现规律:

  1. 当 cnt0 = 2n 或者 cnt1 = 2n 或者 cnt2 = 2n 时,任意两个相邻元素之和肯定不被 3 整除;
  2. 保证1的情况下,当 cnt0 > n 时肯定会有两个余数为 0 的数相邻;
  3. 保证1、2的情况下,当 cnt0 > 3 时肯定会有解;
  4. 当 cnt0 = 2 时,如果 cnt1 \bmod 2 = 0 肯定会有余数为 0 、余数为 1 的数相邻;
  5. 当 cnt0 = 1 或者 cnt0 = 0 时,如果 cnt1 > 0 并且 cnt2 > 0 肯定会有余数为 0 、余数为 1 的数相邻;
  6. 剩下的就是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;
}

管理员,求通过!