Nyist 311 (完全背包)

来源:互联网 发布:中国地质大学网络教育 编辑:程序博客网 时间:2024/06/07 06:59

描述

直接说题意,完全背包定义有N种物品和一个容量为V的背包,每种物品都有无限件可用。第i种物品的体积是c,价值是w。求解将哪些物品装入背包可使这些物品的体积总和不超过背包容量,且价值总和最大。本题要求是背包恰好装满背包时,求出最大价值总和是多少。如果不能恰好装满背包,输出NO

输入

第一行: N 表示有多少组测试数据(N<7)。
接下来每组测试数据的第一行有两个整数M,V。 M表示物品种类的数目,V表示背包的总容量。(0

输出

对应每组测试数据输出结果(如果能恰好装满背包,输出装满背包时背包内物品的最大价值总和。 如果不能恰好装满背包,输出NO)

样例输入

2
1 5
2 2
2 5
2 2
5 1

样例输出

NO
1

状态转移方程:dp[j] = max(dp[j - cost[i]] + value[i], dp[j])

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;const int INF = 0x3f3f3f3f;int cost[2020];int value[2020];int dp[50050];void init(int v){    memset(cost, 0, sizeof(cost));    memset(value, 0, sizeof(value));    for (int i = 1; i <= v; i++)    {        dp[i] = -INF;    }}int main(){    int N;    scanf("%d", &N);    while (N--)    {        int M, V;        scanf("%d%d", &M, &V);        init(V);        for (int i = 1; i <= M; i++)        {            scanf("%d%d", &cost[i], &value[i]);        }        dp[0] = 0;        for (int i = 1; i <= M; i++)        {            for (int j = cost[i]; j <= V; j++)            {                if (j >= cost[i])                {                    dp[j] = max(dp[j - cost[i]] + value[i], dp[j]);                }            }            // for (int i = 0; i <= N; i++)            // {            //     cout << dp[i] << " ";            // }            // cout << "\n";        }        if (dp[V] < 0)        {            cout << "NO"                 << "\n";        }        else        {            cout << dp[V] << "\n";        }    }    return 0;}
原创粉丝点击