51Nod 1085 背包问题
2018-01-17 13:24
260 查看
在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
输出可以容纳的最大价值。
Input示例
3 6
2 5
3 8
4 9
Output示例
14
就是背包裸题,好久没写了,练习下保持下手感.
Input
第1行,2个整数,N和W中间用空格隔开。N为物品的数量,W为背包的容量。(1 <= N <= 100,1 <= W <= 10000)
第2 - N + 1行,每行2个整数,Wi和Pi,分别是物品的体积和物品的价值。(1 <= Wi, Pi <= 10000)
Output
输出可以容纳的最大价值。
Input示例
3 6
2 5
3 8
4 9
Output示例
14
就是背包裸题,好久没写了,练习下保持下手感.
#include <cstdio> #include <iostream> using namespace std; const int maxn = (int)1e4 +10; int w[maxn] , v[maxn]; int dp[105][maxn]; //dp[i][j]前i件物品放入容量为j背包可以获得的最大值 int main(void) { int n , m; cin >> n >> m; for(int i = 1 ; i <= n ; i++){ cin >> w[i] >> v[i]; } for(int i =1 ; i <=n ; i++) for(int j = 0 ; j <= m ; j++) { if(j < w[i]) // 放不下 dp[i][j] = dp[i -1][j]; else { dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - w[i]]+v[i]); } } cout << dp [m] << endl; return 0; }一维:
//dp[]数组里存的是容量为j的最大价值 #include <cstdio> #include <iostream> #include <algorithm> #include <vector> using namespace std; #define fi first #define se second inline pair<int,int> mypair() { int a,b;cin>>a>>b ;return make_pair(a,b); } vector <pair<int,int> > v; int dp[10005]; int main(void) { ios::sync_with_stdio(false);cin.tie(0); int n , w ; cin >> n >> w; for(int i = 0 ; i < n ; i++){ v.push_back(mypair()); } for(int i = 0 ; i< n ; i++) { for(int j = w ; j >= v[i].fi ; j--) { dp[j] = max(dp[j] , dp[j - v[i].fi] + v[i].se); } } cout << dp[w] << endl; return 0; }
相关文章推荐
- 51nod 1085 背包问题【01背包】
- 51Nod-1085 背包问题
- 51Nod-1085-背包问题
- 51Nod 1085 背包问题
- 51Nod 1085 背包问题(01)
- 51nod 1085 背包问题<水过>
- 【51Nod】1085 - 背包问题(01背包)
- 51nod 1085 背包问题01
- 51Nod 1085 背包问题
- 51nod 1085 背包问题(01背包)
- 51Nod 1085 背包问题(01背包 )
- 【51nod 1085】背包问题(0-1背包模板)
- 51Nod:1085 背包问题
- 51nod--1085--背包问题
- 51nod 1085 背包问题
- 【51NOD-0】1085 背包问题
- 51Nod 1085背包问题(dp)
- 51nod 1085 背包问题
- 【51Nod】1085 - 背包问题【01背包】
- 51nod 1085 背包问题【01背包】