*天平问题

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值