Codeforces Round #693 (Div. 3), problem: (B) Fair Division

B. Fair Division
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Alice and Bob received n candies 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 candies are not allowed to be cut in half.

Input
The first line contains one integer t (1≤t≤104) — the number of test cases. Then t test cases follow.

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

The next line contains n integers a1,a2,…,an — the weights of the candies. The weight of each candy is either 1 or 2.

It is guaranteed that the sum of n over all test cases does not exceed 105.

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 strings yEs, yes, Yes and YES will be recognized as positive).

Example
inputCopy
5
2
1 1
2
1 2
4
1 2 1 2
3
2 2 2
3
2 1 2
outputCopy
YES
NO
YES
NO
NO
Note
In the first test case, Alice and Bob can each take one candy, then both will have a total weight of 1.

In the second test case, any division will be unfair.

扫描二维码关注公众号,回复: 12465350 查看本文章

In the third test case, both Alice and Bob can take two candies, one of weight 1 and one of weight 2.

In the fourth test case, it is impossible to divide three identical candies between two people.

In the fifth test case, any division will also be unfair.

本题题意很明显,本题就是对于一系列给定的重为1或2的糖果是否能进行均分,本题的坑点就是两个重为1的糖果刚好可以抵消重为2的糖果的影响

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
    int t;
    cin>>t;
    while(t--)
    {
    
    
        int count1=0,count2=0;
        int n;
        int x;
        cin>>n;
        for(int i=0;i<n;i++)
        {
    
    
            cin>>x;
            if(x&1)
               count1++;
            if(x==2)
               count2++;
        }
        if(count2%2==0)
        {
    
    
            if(count1%2==0)
              cout<<"YES"<<endl;
            else
            {
    
    
                cout<<"NO"<<endl;
            }
            
        }
        else
            {
    
    
                count1-=2;//容易忽略的点
                if(count1>=0&&count1%2==0)
                   cout<<"YES"<<endl;
                else
                   cout<<"NO"<<endl;
            }
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46006714/article/details/113428208
今日推荐