【URAL 1244】Gentlemen(DP+记录路径)

【URAL 1244】Gentlemen(DP+记录路径)

题目大意:
n张卡片,每张有价值。给出一个价值V,问是否有唯一组合方式组合出V。
有的话输出不在组合里的卡牌编号,没有的话输出0,多解输出-1.

01背包+记录一下路径。

要拐的一个弯是,对于当前价值,只记录第一次到达时的物品编号。
之后的多解不再记录。

因为01背包是枚举物品然后递推得到的,如果是唯一解,dp[v]一定不是0或-1。但从0到v的这条路径上,可能有些点被之后新加的物品覆盖变成多解决,但实际上对于得到v是没有影响的。

譬如
4 4
1
1
2
5

在做背包的时候,枚举完前两张卡片 1 1后,dp[1]实际已经变成-1了。但dp[2]在第二次枚举变为1(唯一解),并且记录下卡2。因此,枚举第一张卡的时候,dp[1]处记录卡1是没问题的,最终答案的唯一解/多解 只与dp[v]有关

代码如下:

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <ctime>
#include <cstring>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread(ch) freopen(ch,"r",stdin)
#define fwrite(ch) freopen(ch,"w",stdout)

using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
const double eps = 1e-8;
const int maxm = 112345;
const int maxn = 233;

int dp[maxm];
int pre[maxm];
int num[maxn];
bool vis[maxn];

int main()
{
	fread("in.in");
	fwrite("out.out");

	int v,n;

	scanf("%d%d",&v,&n);

	dp[0] = 1;

	for(int i = 1; i <= n; ++i)
	{
		scanf("%d",&num[i]);
		for(int j = v-num[i]; j >= 0; --j)
		{
			if(dp[j])
			{
				if(dp[j+num[i]] == 0 && dp[j] != -1) 
				{
					dp[j+num[i]] = 1;
					pre[j+num[i]] = i;
				}
				else dp[j+num[i]] = -1;
			}
		}
	}

	
	if(dp[v] > 0)
	{
		int tmp = v;
		while(tmp)
		{
			vis[pre[tmp]] = 1;
			tmp -= num[pre[tmp]];
		}

		bool f = 0;
		for(int i = 1; i <= n; ++i)
		{
			if(vis[i]) continue;
			if(f) putchar(' ');
			else f = 1;
			printf("%d",i);
		}
	}
	else printf("%d",dp[v]);
	puts("");

	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值