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
题意,给你一些砝码,如3个砝码1 2 4,要求你用这些砝码称出从1到砝码之和的重量,其中不能称出的重量就要输出出来
很显然1 2 4可以称出从1到7的所有重量,输出0
9 2 1首先按左物右码可以输出1 2 3 10 11 12,而6 7 8可以是6+1=2=9,7+2=9,8+1=9
所以输出4 5
解法:可以使用DP做,dp(i)代表这个i值是否可以称出来,0代表这个可以称,1代表不可以,然后初始赋值为dp(0)=0显然重量为0是可称的,后来的判断也要先以此为基石,再把其他的所有dp(i)赋值为1,代表这个数还没开始测试,当然是不可称的状态,然后再开始具体工作
1.先按左物右码的原理开始模拟,测出那些可以由此原理测出的数字
dp(j)=min{dp(j-a(i)),dp(j)}
2.再按照右边放一个砝码,左边往待测物体上加砝码开始测试
dp(j)=min{dp(j+a(i)),dp(j)}
最后再输出那些值为1的序号
#include"iostream" #include"cstring" using namespace std; int a[101]; int book[10001],ans[10001]; int m,n; void Work() { for(int i=0;i<n;i++) for(int j=m;j>=a[i];j--) { book[j]=min(book[j],book[j-a[i]]); } for(int i=0;i<n;i++) for(int j=0;j<=m-a[i];j++) { book[j]=min(book[j],book[j+a[i]]); } int top=0; for(int i=1;i<=m;i++) if(book[i]==1) ans[top++]=i; cout<<top<<endl; if(top) { for(int j=0;j<top-1;j++) cout<<ans[j]<<" "; cout<<ans[top-1]<<endl; } } int main() { while(cin>>n) { m=0; memset(book,0,sizeof(book)); for(int i=0;i<n;i++) {cin>>a[i];m+=a[i];} for(int j=1;j<=m;j++) book[j]=1; book[0]=0; Work(); } return 0; }
O(O—O)O