1. 程式人生 > 實用技巧 >【題解】Fair Division【水題】

【題解】Fair Division【水題】

B. Fair Division

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Alice and Bob receivednncandies from their parents.Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.

Check if they can do that.

Note that candiesare not allowed to be cut in half.

Input

The first line contains one integertt(1≤t≤1e4)— the number of test cases. Thentttest cases follow.

The first line of each test case contains an integernn(1≤n≤100)— the number of candies that Alice and Bob received.

The next line containsnnintegersa1,a2,…,an— the weights of the candies. The weight of each candy is either1or2

It is guaranteed that the sum ofnnover all test cases does not exceed1e5

Output

For each test case, output on a separate line:

  • "YES", if all candies can be divided into two sets with the same weight;
  • "NO" otherwise.

You can output "YES" and "NO" in any case (for example, the stringsyEs,yes,YesandYESwill be recognized as positive).

題目大意:

有n根蠟燭,重量為1克或2克,現在把這些蠟燭分給兩個人,判斷能否使兩人分得的重量相等。

題目分析:

直接模擬分蠟燭的過程,先分2克的蠟燭,再分1克的蠟燭。那麼有這幾種情況:

1、2克的蠟燭有偶數個,1克的蠟燭有偶數個。可以均分。

2、2克的蠟燭有偶數個,1克的蠟燭有奇數個。不可均分。

3、2克的蠟燭有奇數個,1克的蠟燭少於2個。不可均分。

4、2克的蠟燭有奇數個,1克的蠟燭多於2個且為奇數。不可均分。

5、2克的蠟燭有奇數個,1克的蠟燭多於2個且為偶數。可以均分。

直接統計兩種蠟燭的數量,根據上述情況判斷即可。

程式碼實現:

#include <bits/stdc++.h>
using namespace std;
int t;
int n;
int a,b;
int c;
int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        a=0;
        b=0;
        for(int i=1;i<=n;i++){
            scanf("%d",&c);
            if(c==1)a++;
            if(c==2)b++;
        }
        if(b%2==0){
            if(a%2==0)printf("YES\n");
            else printf("NO\n");
        }
        if(b%2!=0){
            if(a<2)printf("NO\n");
            else{
                if(a%2==0)printf("YES\n");
                else printf("NO\n");
            }
        }
    }
    return 0;
}