[Codeforces Round #248 (Div. 2)] A. Kitahara Haruki's Gift
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
The first line contains an integer n (1 ≤ n ≤ 100) — the number of apples. The second line contains n integers w1, w2, ..., wn (wi = 100 or wi = 200), where wi is the weight of the i-th apple.
In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).
3
100 200 100
YES
4
100 100 100 200
NO
In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa.
题解:转化为背包问题,背包容量为所有苹果总重量的一半,看是否能装满。因为不是100就是200,所以每个苹果重量和背包总容量都可以除以100来优化内存。
代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdbool.h> 4 #include<stdlib.h> 5 #include<math.h> 6 #include<ctype.h> 7 #include<time.h> 8 9 #define rep(i,a,b) for(i=(a);i<=(b);i++) 10 #define red(i,a,b) for(i=(a);i>=(b);i--) 11 #define sqr(x) ((x)*(x)) 12 #define clr(x,y) memset(x,y,sizeof(x)) 13 #define LL long long 14 15 int i,j,n,m,sum, 16 f[205],a[100]; 17 18 int main() 19 { 20 int i; 21 22 clr(f,-1); 23 f[0]=0; 24 25 scanf("%d",&n); 26 27 rep(i,1,n){ 28 scanf("%d",&a[i]); 29 a[i]/=100; 30 sum+=a[i]; 31 } 32 33 if(sum%2!=0){ 34 printf("NO\n"); 35 exit(0); 36 } 37 38 sum/=2; 39 rep(i,1,n) 40 rep(j,0,sum-a[i]){ 41 if(f[j]!=-1) 42 f[j+a[i]]=f[j]; 43 } 44 45 if(f[sum]==0) printf("YES"); 46 else printf("NO"); 47 48 49 return 0; 50 }