Algorithm Improvement 01 Backpack

.

  Algorithm Improvement 01 Backpack  
Time limit: 1.0s Memory limit: 256.0MB
    
Problem Description
  Given N items, each item has a weight W and a value V. You have a backpack that can hold a weight M. Ask how to load it to maximize the value. Each item has only one.
input format
  The first line of input contains two integers n, m, which represent the number of items and the weight of the backpack, respectively.
  In the next N lines, there are two numbers Wi and Vi in each line, indicating the weight and value of the item
output format
  Output 1 line containing an integer representing the maximum value.
sample input
3 5
2 3
3 5
4 7
Sample output
8
Data size and conventions
  1<=N<=200,M<=5000.

Idea: 01 Knapsack problem, written with dynamic programming (tabulation).

    

//01 Knapsack problem
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;
int volume[300];
int needed[300];
int cache[6000][300];//The tabulation method of dynamic programming
int PK(int capacity,int item) {
	if (item==-1) {//Boundary conditions
		return 0;
	}
	int &ret = cache[capacity][item];
	if (ret! = 0) {
		return ret;
	}
	//When the item is not put in
	ret=PK(capacity,item-1);
	// when the item is put in
	if (capacity>=volume[item]) {
		ret = max(ret, PK(capacity - volume[item],item-1) + needed[item]);
	}
	return ret;
}
int main() {
	int n, m;
		cin >> n >> m;
		for (int i = 0; i < n;i++) {
			cin >> volume[i];
			cin >> needed[i];
		}
		cout<<PK(m,n-1);
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325695249&siteId=291194637