Description
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整除。
思路
这是一道思维题,首先要明白不能让两数之和被3整除,那么不难想到这两个数字必须满足以下条件:两数分别对3取余之和不能为3,即不能是1和2;两数对3取余不能同时为0。也就是说只有当两数对3取余为1和1,2和2,0和1,或者0、2时满足条件。
由此我们可以得到不能使对3取余为0、0或者1、2的两数相邻。
可以得到以下情况时为符合条件的情况(方便起见以下0、1、2代表对3取余为0、1、2的数字):
①
…1 1 1 0 2 2 2 …
…1 1 1 1 0 1 1 …
也就是:2与1不相互接触,用0分隔开,且0只有两个。
②
只有0、1或者0、2,且0的数目小于n(即一行)。
③
只剩下1或2
#include <stdio.h>
int main()
{
int t;
int mod0=0,mod1=0,mod2=0;
scanf("%d",&t);
while(t--)
{
int n;
int i;
mod0=0;mod1=0;mod2=0;
scanf("%d",&n);
for(i=0;i<2*n;i++)
{
int x;
scanf("%d",&x);
if(x%3==0)
mod0++;
else if(x%3==1)
mod1++;
else
mod2++;
}
if(mod0>n || (mod0<=1 && mod1 && mod2))// 0数目大于n 以及 排除只剩下剩下1和2的情况
printf("NO\n");
else if(mod1==0 || mod2==0)// 只剩下0、1或者0、2的情况
printf("YES\n");
else if(mod0==2 && mod1%2==0 && mod2%2==0)// 2与1不相互接触,用0分隔开,且0只有两个的情况
printf("NO\n");
else
printf("YES\n");
}
}