51Nod 1085 01背包

01背包入门题,刚学完当写模板。

在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。

Input第1行,2个整数,N和W中间用空格隔开。N为物品的数量,W为背包的容量。(1 <= N <= 100,1 <= W <= 10000)
第2 - N + 1行,每行2个整数,Wi和Pi,分别是物品的体积和物品的价值。(1 <= Wi, Pi <= 10000)Output输出可以容纳的最大价值。

Sample Input

3 6
2 5
3 8
4 9

Sample Output

14

 1 #include<iostream>
 2 #include<stdio.h>
 3 using namespace std;
 4 int dp[105][10050];
 5 int main()
 6 {
 7     int n,v,x,y;
 8     cin>>n>>v;
 9     for(int i=1;i<=n;i++)
10     {
11         scanf("%d%d",&x,&y);
12         for(int j=0;j<=v;j++)
13         {
14             dp[i][j]=dp[i-1][j];
15             if(j>=x)
16             {
17                 dp[i][j]=max(dp[i-1][j],dp[i-1][j-x]+y);
18             }
19         }
20     }
21     printf("%d\n",dp[n][v]);
22     return 0;
23 
24 }



原文地址:https://www.cnblogs.com/ISGuXing/p/7209024.html