【题解】Fair Division【水题】
链接:https://codeforces.com/contest/1472/problem/B
B. Fair Division
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Alice and Bob received nn 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 tt (1≤t≤1e4) — the number of test cases. Then tt test cases follow.
The first line of each test case contains an integer nn (1≤n≤100) — the number of candies that Alice and Bob received.
The next line contains nn 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 nn over all test cases does not exceed 1e5
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).
题目大意:
有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; }

浙公网安备 33010602011771号