The Balance
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4595 Accepted Submission(s): 1841
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
题目大意说给你一些砝码问你能称出多少种不同重量的物品。
直接背包算出用砝码直接能组成的重量。在加上直接组合相减能得到的重量。不用担心一个砝码被两边使用。比如。有a,b,c三个砝码。a+b,和a+c。a被使用了两次。但相减后a就减掉了。不会造成影响。
写了两种版本的背包核心思想都一样。
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int w[150],f[10100],vis[10010],ans[10010];
int maxx(int a,int b)
{
return a>b?a:b;
}
int main()
{
int i,j,n,ma,cnt;
while(~scanf("%d",&n))
{
ma=0;
cnt=0;
for(i=0; i<n; i++)
{
scanf("%d",&w[i]);
ma+=w[i];
}
memset(f,0,sizeof f);
memset(vis,0,sizeof vis);
for(i=0; i<n; i++)
for(j=ma; j>=w[i]; j--)//把权重和价值设为相等。若该值能直接的到则背包的值就为本身。否则为该背包通过组合能得到的最大值
f[j]=maxx(f[j],f[j-w[i]]+w[i]);
for(i=1;i<=ma;i++)
{
if(f[i]==i)
{
vis[i]=1;//把直接组合能得到的值加以标记
for(j=i+1;j<=ma;j++)
if(f[j]==j)
vis[j-i]=1;//把相减能得到的值也加以标记
}
}
for(i=1; i<=ma; i++)
if(!vis[i])
ans[cnt++]=i;//把答案。计入数组
printf("%d\n",cnt);
if(cnt>0)
{
for(i=0; i<cnt-1; i++)//输出答案
printf("%d ",ans[i]);
printf("%d\n",ans[i]);
}
}
return 0;
}
第二版
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int w[150],f[10100],vis[10010],ans[10010];
int main()
{
int i,j,n,ma,cnt;
while(~scanf("%d",&n))
{
ma=0;
cnt=0;
for(i=0; i<n; i++)
{
scanf("%d",&w[i]);
ma+=w[i];
}
memset(f,0,sizeof f);
memset(vis,0,sizeof vis);
f[0]=1;
for(i=0; i<n; i++)
for(j=ma; j>=w[i]; j--)
f[j]+=f[j-w[i]];//直接算出每种值有多少种组合方法
for(i=1;i<=ma;i++)
{
if(f[i])
{
vis[i]=1;
for(j=i+1;j<=ma;j++)
if(f[j])//如果能组合得到
vis[j-i]=1;
}
}
for(i=1; i<=ma; i++)
if(!vis[i])
ans[cnt++]=i;
printf("%d\n",cnt);
if(cnt>0)
{
for(i=0; i<cnt-1; i++)
printf("%d ",ans[i]);
printf("%d\n",ans[i]);
}
}
return 0;
}