The Balance
Time
Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K
(Java/Others)
Total Submission(s): 2410 Accepted Submission(s):
959
Problem Description
Now you are asked to measure a dose of medicine with a
balance and a number of weights. Certainly it is not always achievable. So you
should find out the qualities which cannot be measured from the range [1,S]. S
is the total quality of all the weights.
Input
The input consists of multiple test cases, and each
case begins with a single positive integer N (1<=N<=100) on a line by
itself indicating the number of weights you have. Followed by N integers Ai
(1<=i<=N), indicating the quality of each weight where
1<=Ai<=100.
Output
For each input set, you should first print a line
specifying the number of qualities which cannot be measured. Then print another
line which consists all the irrealizable qualities if the number is not
zero.
Sample Input
3
1 2 4
3
9 2 1
Sample Output
0
2
4 5
Source
Recommend
lcy
每种砝码既可以放在右盘,又可以放在左盘,(若按左物右码来说),放在左盘那就取减号,放在右盘就取加号。
1 #include<stdio.h>
2 int c1[10001] , c2[10001] ;
3 int counts , n , num[101] , sum , nfind[10001] ;
4 int main ()
5 {
6 while ( scanf( "%d" , &n ) != EOF )
7 {
8 sum = 0 , counts = 0 ;
9 for ( int i = 1 ; i <= n ; ++ i )
10 {
11 scanf ( "%d" , num + i ) ;
12 sum += num[i] ;
13 }
14 for ( int i = 0 ; i <= sum ; ++ i )
15 {
16 c1[i] = 0 ;
17 c2[i] = 0 ;
18 }
19 c1[0] = c1[num[1]] = 1 ;
20 for ( int i = 2 ; i <= n ; ++ i )
21 {
22 for ( int j = 0 ; j <= sum ; ++ j )
23 for ( int k = 0 ; j + k <= sum && k <= num[i] ; k += num[i] )
24 {
25 if ( j >= k ) c2[j-k] += c1[j] ;
26 else c2[k-j] += c1[j] ;
27 c2[k+j] += c1[j] ;
28 }
29 for ( int j = 0 ; j <= sum ; ++ j )
30 c1[j] = c2[j] , c2[j] = 0 ;
31 }
32 for ( int i = 1 , j = 0 ; i <= sum ; ++ i )
33 {
34 if ( c1[i] == 0 )
35 {
36 counts ++ ;
37 nfind[j++] = i ;
38 }
39 }
40 if ( counts == 0 ) printf ( "0\n" ) ;
41 else {
42 printf ( "%d\n" , counts ) ;
43 for ( int j = 0 ; j < counts ; ++ j )
44 printf ( "%d%c" , nfind[j] , j + 1 == counts ? '\n' : ' ' ) ;
45 }
46 }
47 return 0 ;
48 }