题目描述
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.
有N件物品和一个容量为V的背包。第i件物品的重量是c[i],价值是w[i]。求解将哪些物品装入背包可使这些物品的重量总和不超过背包容量,且价值总和最大。
输入输出格式
输入格式:-
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
- Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints
输入输出样例
输入样例#1:
4 6 1 4 2 6 3 12 2 7
输出样例#1:
23
虽然是裸的背包,但是这个不能用二维,会爆
然后自己手推了一下一维的,,
貌似还能更短。。。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 using namespace std; 6 void read(int & n) 7 { 8 char c='+';int x=0;int flag=0; 9 while(c<'0'||c>'9') 10 { 11 c=getchar(); 12 if(c=='-') 13 flag=1; 14 } 15 while(c>='0'&&c<='9') 16 x=x*10+(c-48),c=getchar(); 17 flag==1?n=-x:n=x; 18 } 19 const int MAXN=1000001; 20 int n,maxt; 21 struct node 22 { 23 int w; 24 int v; 25 }a[MAXN]; 26 int dp[MAXN]; 27 int main() 28 { 29 read(n);read(maxt); 30 for(int i=1;i<=n;i++) 31 { 32 read(a[i].w);read(a[i].v); 33 } 34 for(int i=1;i<=n;i++) 35 { 36 for(int j=maxt;j>=0;j--) 37 { 38 if(a[i].w<=j) 39 dp[j]=max(dp[j],dp[j-a[i].w]+a[i].v); 40 else 41 dp[j]=dp[j]; 42 } 43 } 44 cout<<dp[maxt]; 45 return 0; 46 }