1. 程式人生 > >ACM-ICPC 2017 Asia Nanning-J:Rearrangement(思維)

ACM-ICPC 2017 Asia Nanning-J: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(1t200) which is the number of test cases.

In each case, the first line contains an integers n (1 \le n \le 10000)n(1n10000) 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 1000000

1000000.

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
思路:可以把數分成三種:即除3的餘數分別為0,1,2。那麼餘數為1,2的2種數不能相鄰,餘數為0,0的2種數不能相鄰。那麼可以考慮餘數為1的數放在最左邊,餘數為2的數放在最右邊,餘數為0的數放在中間。如圖:

1

1

1

0

2

2

2

2

1

1

1

1

0

2

2

2

 不過還有些細節要處理。

#include<bits/stdc++.h>
using namespace std;
int a[4];
int main()
{
    int T;cin>>T;
    while(T--)
    {
        int n;
        scanf("%d",&n);
        memset(a,0,sizeof a);
        for(int i=1;i<=2*n;i++)
        {
            int x;
            scanf("%d",&x);
            a[x%3]++;
        }
        if(a[0]>n)puts("NO");//當0的個數大於n,必定有2個0相鄰
        else
        {
            if(a[0]<=1&&a[1]&&a[2])puts("NO");//當0的個數小於等於1時,必定有1個1和1個2相鄰
            else if(a[1]==0||a[2]==0)puts("YES");
            else if(a[0]>=2&&a[1]&&a[2])
            {
                if(a[0]==2&&a[1]%2==0&&a[2]%2==0)puts("NO");//當只有2個0且1和2的個數均為偶數時,必定有1個1和1個2相鄰
                else puts("YES");
            }
        }
    }
    return 0;
}