ACM-ICPC 2017 Asia Nanning j题 Rearrangement【思维】


传送门:Rearrangement


Rearrangement

In a two dimensional array of integers of size 2 \times n2×n, is it possible to rearrange integers so that the sum of two adjacent elements (which are adjacent in a common row or a common column) is never divisible by three?

Input
The input has several test cases and the first line contains an integer t (1 \le t \le 200)t(1≤t≤200) which is the number of test cases.

In each case, the first line contains an integers n (1 \le n \le 10000)n(1≤n≤10000) indicating the number of columns in the array. The second line contains the elements of the array in the first row separated by single spaces. The third line contains the elements of the array in the second row separated by single spaces. The elements will be positive integers less then 10000001000000.

Output
For each test case, output “YES” in a single line if any valid rearrangement exists, or “NO” if not.

样例输入

6
3
3 6 9
1 4 7
3
3 6 9
1 3 8
5
1 2 3 4 5
6 7 8 9 10
10
1 1 1 1 1 1 1 1 1 1
2 3 2 3 2 3 2 3 2 3
2
3 1
2 3
2
3 1
1 2

样例输出

YES
NO
YES
YES
YES
NO



解题思路:
先将 2*n 个数对 3 取模,很明显的是所有的数会变成 0、1、2 三个数,那么相邻的两个数不可以是:0 - 0,1 - 2 。

因为 1 和 2 不能相邻所有我们可以将他们一个放左边,一个放右边,0 放中间。(可进行 0 - 1 、
0 - 2 的匹配)
首先判断一下 0 的个数,如果 0 的数目大于 n 的话,肯定会出现一个 0 - 0 组合。

然后判断是否有 1 的个数是 0 或者 2 的个数是 0 的情况,因为 0 的个数一定小于等于 n 了,一旦有一个等于0,另个数就可以和 0 匹配完,这样就一定可以,输出 YES

如果 0 的数目小于等于 1 ,并且 1 和 2 的数目不等于 0 的话,就一定会出现 1 - 2 的组合。


AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=11000;
int t;
int n;
int a[2][N],sum[4];
int main()
{
  scanf("%d",&t);
  while(t--)
  {
    memset(sum,0,sizeof(sum));
    scanf("%d",&n);
    for(int i=0;i<2;i++)
    {
      for(int j=0;j<n;j++)
      {
        scanf("%d",&a[i][j]);
        sum[a[i][j]%3]++;
      }
    }
    if(sum[0]>n)
      printf("NO\n");
    else
    {
      if(sum[0]<=1&&sum[1]&&sum[2])
        printf("NO\n");
      else if(sum[1]==0||sum[2]==0)
        printf("YES\n");
      else if(sum[0]>=2&&sum[1]&&sum[2])
      {
        if(sum[0]==2&&sum[1]%2==0&&sum[2]%2==0)//特殊情况,一定会出现1 - 2 的组合
          printf("NO\n");
        else
          printf("YES\n");
      }
    }
  }
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值