您的位置:首页 > 其它

基础01背包问题

2015-04-13 20:04 267 查看
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1085
http://hihocoder.com/problemset/problem/1038?sid=320857
在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。

动态转移方程 dp[i][j]=max(dp[i-1][j],dp[i-1][j-v[i]]+w[i]);

背包九讲里面讲的很好。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>

#define CL(arr, val)    memset(arr, val, sizeof(arr))

#define ll long long
#define inf 0x7f7f7f7f
#define lc l,m,rt<<1
#define rc m + 1,r,rt<<1|1
#define pi acos(-1.0)

#define L(x)    (x) << 1
#define R(x)    (x) << 1 | 1
#define MID(l, r)   (l + r) >> 1
#define Min(x, y)   (x) < (y) ? (x) : (y)
#define Max(x, y)   (x) < (y) ? (y) : (x)
#define E(x)        (1 << (x))
#define iabs(x)     (x) < 0 ? -(x) : (x)
#define OUT(x)  printf("%I64d\n", x)
#define lowbit(x)   (x)&(-x)
#define Read()  freopen("a.txt", "r", stdin)
#define Write() freopen("b.txt", "w", stdout);
#define maxn 1000000000
#define N 100010
using namespace std;

int n,m;
int f
;
void ZeroOnePack(int cost,int weight)
{
for(int v=m;v>=cost;v--)
f[v]=max(f[v],f[v-cost]+weight);
}
int main()
{
//Read();
//Write();
int a,b;
while(~scanf("%d%d",&n,&m))
{
memset(f,0,sizeof(f));
for(int i=0;i<n;i++)
{
scanf("%d%d",&a,&b);
ZeroOnePack(a,b);
}
printf("%d\n",f[m]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: