Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 28069 | Accepted: 12627 |
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
* Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di
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
题目大意:这里有N个礼品和一个可以装下重M的礼品的袋子,求一下这个袋子最多能装下价值多少的礼品。其中第一行输入N和M的值,就是N个礼品的数量和袋子的承重量。接下来的N行是每种礼品的重量和礼品的价值。求这个袋子做多能装下价值多少的礼品。
本题思路:这是一道0 1背包问题,同时也是一道非常简单的模板题。对于0 1背包,其中最核心的代码就是
for(int i=1;i<=n;i++)
{
for(int j=m;j>=w[i];j--)
{
f[j]=max(f[j],f[j-w[i]]+v[i])
}
}
其中 f[j]=max(f[j],f[j-w[i]]+v[i]是状态转移方程,f[j]表示前i件物品的总价值。
其中对于0 1背包,每件物品你必须取或者不取,且每种物品只能取一次,这就是0 1背包问题,不同于完全背包。
AC代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int n,V,f[13000],w[500],v[110];
while(scanf("%d %d",&n,&V)!=EOF)
{
for(int i=1;i<=n;i++)
scanf("%d %d",&w[i],&v[i]);
for(int i=0;i<=V;i++)
f[i]=0;
for(int i=1;i<=n;i++)
{
for(int j=V;j>=w[i];j--)
{
if(f[j]<f[j],f[j-w[i]]+v[i])
f[j]=max(f[j],f[j-w[i]]+v[i]);
}
}
printf("%d\n",f[V]);
}
}