hiho1043(无限物品的背包问题)

题目链接:http://hihocoder.com/problemset/problem/1043

代码如下:

#include 
#include 
#include 

using namespace std;

const int maxn= 500 + 10;

int need[maxn],value[maxn],dp[100000+5],N,M;

int dpBag(int S) {
    int& ans = dp[S];
    if(ans >= 0) {
        return ans;
    }
    ans = 0;
    for(int i = 1; i <= N; i++) {
        if(S >= need[i]) {
            ans = max(ans, dpBag(S - need[i]) + value[i]);
        }
    }
    return ans;
}


int main()
{
    while(scanf("%d%d",&N,&M)!=EOF)
    {
        memset(dp,-1,sizeof(dp));
        for(int i=1; i<=N; i++)
            scanf("%d%d",&need[i],&value[i]);
        printf("%d\n",dpBag(M));
    }
    return 0;
}

你可能感兴趣的:(#,dp,dp,hiho1043,无限物品,背包)