母函数——秤砣问题——The Balance

该问题探讨如何使用一组重量的秤砣测量不同质量的药物剂量。输入包含秤砣的数量及其重量,目标是找出在不超过总重量S的情况下无法测量的质量。输出是不可测量的质量数及其具体值。示例说明了如何通过秤砣组合来确定可测量的质量范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:给你一些秤砣,找出在不超过重质量的情况下,哪些重量是称不出来的

考虑一个特殊的情况: 给你一个1,一个2,要想称出1,很明显放一个重量为1的即可,但是天平左边放1,右边放2,同样可以称出1;

可以称出的质量还可得到这样一个式子 M=\left | m1-m2 \right | ; m1,m2 分别为两个秤砣重量;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=20000;
int n;
int a[maxn];
int t[maxn];
int v[maxn];

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int s=0;
        memset(t,0,sizeof t);
        memset(v,0,sizeof v);
        for(int i=1;i<=n;++i)
            scanf("%d",&a[i]),s+=a[i];
        v[0]=1;
        v[a[1]]=1;
        for(int i=2;i<=n;++i)
        {
            for(int j=0;j<=s;++j)
                for(int k=0;k+j<=s&&k<=a[i];k+=a[i])
            {
                t[abs(j-k)] += v[j];
                t[j+k]+=v[j];
            }
            for(int j=0;j<=s;++j)
            {
                v[j]=t[j];
                t[j]=0;
            }
        }
        int cnt=0;
        for(int i=0;i<=s;++i)
            if(v[i]==0) ++cnt;
        cout<<cnt<<endl;
        if(cnt==0) continue;
        else
        {
            for(int i=0;i<=s;++i)
            {
                if(!v[i])
                {
                    printf("%d",i);
                    --cnt;
                    if(cnt) printf(" ");
                    else puts("");
                }
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值