nyist 311 完全背包

题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=311

思路:

AC代码1:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int dp[50010];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int m,v;
        memset(dp,-1,sizeof(dp));
        dp[0] = 0;
        scanf("%d%d",&m,&v);
        for(int i=1; i<=m; i++)
        {
            int c,w;
            scanf("%d%d",&c,&w);
            for(int j=c; j<=v; j++)
            {
                if(dp[j-c] != -1)
                {
                    dp[j] = max(dp[j],dp[j-c] + w);
                }
            }
        }
        if(dp[v] != -1)
            printf("%d\n",dp[v]);
        else
            printf("NO\n");
    }
    return 0;
}

AC代码2:(初始化为一个很大的负数,上一种方法比较好)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int dp[50010];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int m,v;
        memset(dp,-inf,sizeof(dp));
        dp[0] = 0;
        scanf("%d%d",&m,&v);
        for(int i=1; i<=m; i++)
        {
            int c,w;
            scanf("%d%d",&c,&w);
            for(int j=c; j<=v; j++)
            {
                dp[j] = max(dp[j],dp[j-c] + w);
            }
        }
        if(dp[v] > 0)
            printf("%d\n",dp[v]);
        else
            printf("NO\n");
    }
    return 0;
}







你可能感兴趣的:(nyist 311 完全背包)