# Hdu 2162 Buy the souvenirs(一个求最优解总数的01背包题)

				if(dp[j - v[i]]+1>dp[j]){
dp[j] = dp[j - v[i]] + 1;
G[j] =  G[j - v[i]];
}
else if(dp[j - v[i]]+1==dp[j]){
G[j] += G[j - v[i]];
}

(1)更新G[i][j] = G[i-1][j-v[i]];

(2)增加G[i][j] = G[i-1][j] + G[i-1][j-v[i]];

(3)不变G[i][j] = G[i-1][j];

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <ctime>
#include <cmath>

using namespace std;
const int INF = 0x7fffffff;

int dp[505];
int G[505];
int v[35];
int main()
{
//freopen("/home/user/桌面/in","r",stdin);
int ca;
scanf("%d",&ca);
while(ca--){
memset(dp,0,sizeof(dp));
memset(G,0,sizeof(G));
dp[0] = 0;

int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i) scanf("%d",&v[i]);

G[0]=1;
for(int i=1;i<=n;++i){
for(int j=m;j>=v[i];--j){
if(dp[j - v[i]]+1>dp[j]){
dp[j] = dp[j - v[i]] + 1;
G[j] =  G[j - v[i]];
}
else if(dp[j - v[i]]+1==dp[j]){
G[j] += G[j - v[i]];
}
}
}
//		for(int i=0;i<=m;++i){
//			cout<<"  G["<<i<<"]:"<<G[i]<<"  dp["<<i<<"]:"<<dp[i]<<endl;
//		}
int mk=dp[m],se=0;
for(int i=0;i<=m;++i){
if(dp[i] == mk){
se += G[i];
}
}
if(dp[m] > 0)printf("You have %d selection(s) to buy with %d kind(s) of souvenirs.\n",se,dp[m]);
else printf("Sorry, you can't buy anything.\n");
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Hdu 2162 Buy the souvenirs(一个求最优解总数的01背包题) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)