您的位置:首页 > 其它

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

2016-10-10 21:04 369 查看
【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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: