1008: The Balance
Time Limit: 1000 MS Memory Limit: 32 MB 64bit IO Format: %I64d
Submitted: 11 Accepted: 8
[Submit][Status][Web Board]
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
起初我还天真的认为可以不需要中间变量数组,但事实告诉我,不用中间变量数组C会导致数据的重复计算,导致结果错误。
#include <stdio.h>
#include <stdlib.h>
int a[109],b[100009],c[100009];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
for(int i=0;i<=sum;i++)
{
b[i]=0;
c[i]=0;
}
b[0]=1;
for(int i=1;i<=n;i++)//逐一对已有的砝码枚举,防止重复使用
{
for(int j=0;j+a[i]<=sum;j++)
{
if(b[j])//表示可以用先前的砝码称出的重量
{
c[j]=1;//砝码可以只放一个
c[j+a[i]]=1;//都放在一边
c[abs(j-a[i])]=1;//分别放在两边
}
}
for(int k=1;k<=sum;k++)
{
b[k]=c[k];
c[k]=0;
}
}
int cnt=0;
for(int i=1;i<=sum;i++)
{
// printf("--%d\n",b[i]);
if(!b[i])
{
c[cnt++]=i;
}
}
if(!cnt)
printf("0\n");
else
{
printf("%d\n",cnt);
for(int i=0;i<cnt-1;i++)
{
printf("%d ",c[i]);
}
printf("%d\n",c[cnt-1]);
}
}
return 0;
}