Charm Bracelet
Description Bessie has gone to the mall's jewelry store and spies a charm bracelet. Of course, she'd like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weight Wi (1 ≤ Wi ≤ 400), a 'desirability' factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880). Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings. Input * Line 1: Two space-separated integers: N and M Output * Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints Sample Input 4 6 1 4 2 6 3 12 2 7 Sample Output 23 Source |
题目大意:给你背包的大小,同时给你n件物品及其重量和价值,要求算出最大价值
解题思路:最近开始恶补DP,这段时间上传的会是一些背包问题,今天上传的是01背包,01背包主要是针对一个i来说,只有要或者不要两种情况,所以就根据给的背包大小给出要和不要的情况及其选择后对剩下的物品的一个影响,就目前来看针对01背包我所总结的就是,找到到底谁是背包,然后根据物品循环遍历,里面套着针对背包限制的循环,两层循环完成
这道题就很明显谁是背包谁是限制,所以他的转化方程就是dp[i]=max(dp[i],dp[i-w[j]]+v[j]]),其中w[j]就是j物品的重量,v[j]为j物品的价值
#include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>
#include<cstdio>
#include<climits>
#include<cmath>
#include<vector>
#include <bitset>
#include<algorithm>
#include <queue>
#include<map>
using namespace std;
int main()
{
long long int n, m, i, j, dp[40000], v[40000], w[40000];
cin >> n >> m;
for (i = 1; i <= n; i++)
{
cin >> v[i] >> w[i];
}
memset(dp, 0, sizeof(dp));
for (i = 1; i <= n; i++)
{
for (j = m; j >= v[i]; j--)
{
dp[j] = max(dp[j], dp[j - v[i]] + w[i]);
}
}
cout << dp[m] << endl;
}