2017 HDU 6092 多校联合赛 Rikka with Subset

本文介绍了一道有趣的算法题目:已知一个数组的所有子集的和的个数,反推原始数组。通过动态规划的方法,逐步求解出原始数组的元素。文章提供了完整的解题思路及代码实现。

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

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some

math tasks to practice. There is one of them:

Yuta has nn positive A1−An and their sum is m. Then for each subset S of A, Yuta

calculates the sum of S.

Now, Yuta has got 2n numbers between [0,m] For each i∈[0,m] he counts the number of

i s he got as Bi.

Yuta shows Rikka the array Bi and he wants Rikka to restore A1−An

It is too difficult for Rikka. Can you help her?

Input

The first line contains a number t(1≤t≤70), the number of the testcases.

For each testcase, the first line contains two numbers n,m(1≤n≤50,1≤m≤10e4)

The second line contains m+1 numbers B0−Bm(0≤Bi≤2n)

Output

For each testcase, print a single line with n numbers A1−An.

It is guaranteed that there exists at least one solution. And if there are different solutions, print the

lexicographic minimum one.

Sample Input

2
2 3
1 1 1 1
3 3
1 3 3 1

Sample Output

1 2
1 1 1

Hint

In the first sample, A is [1,2]. A has four subsets [],[1],[2],[1,2] and the sums of each subset

are 0,1,2,3. So B=[1,1,1,1]

题意:

有两个数组a[ ]和b[ ],给出两个数n和m,表示a[ ]中有 n 个数,所有数之和为 m ,然后又给出了b[ ]数组,

b[ x ]数组中装的是a[ ]中和为 x 的子集个数。例如:a[ ]数组为[ 1,2 ];那么它的子集有[ ],[ 1 ],[ 2 ],

[ 1,2 ];这些子集的和分别为 0,1,2,3;所以b[ 0 ]=1,b[ 1 ]=1,b[ 2 ]=1,b[ 3 ]=1;现在给你b[

]数组,让你求a[ ]数组。

思路:

一个很好的DP题目,以前做过一个用零钱凑总共钱数的问题,这个题目反向,由总钱数求零钱。dp[ x ]中

装的是由小数加和而成的 x 有多少个,然后b[ x ]-dp[ x ]就是真正有多少个 x,然后在再用求出的 x 个数与

前面的小数继续组合求和,不断更新dp[ ]。

代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int Max = 10e4+10;
int dp[Max];
int a[55];
int b[Max];
int num[Max];
int t,n,m;
void work()
{
    dp[0]=1;
    int ant=1;
    for(int i=1;i<=m;i++)
    {
        num[i]=b[i]-dp[i];
        for(int u=1;u<=num[i];u++)
        {
            a[ant++]=i;
            for(int j=m;j>=i;j--)
            {
                dp[j]=dp[j]+dp[j-i];
            }
        }
    }
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,0,sizeof(dp));
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(num,0,sizeof(num));
        scanf("%d%d",&n,&m);
        for(int i=0;i<m+1;i++)
        {
            scanf("%d",&b[i]);
        }
        work();
        for(int i=1;i<=n;i++)
        {
            printf("%d%c",a[i],i==n?'\n':' ');
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值