"Algorithms October" (knapsack problem)

Problem Description:

 

2. Analysis: You can know meet a recursive

Definitions: B (I, J): There are a few representative of items I can steal

          J represents the left is how much bag space

 

 E.g:

  If B (4,20) on behalf of: 4 steal items, as well as the remaining space backpack 20 ---> a series of calculations ----> 26

 

 3. Define an array B:

 

4. code shows: 

#include <iostream>
#include <iomanip> 
#include <math.h>
#include <string.h>
#define N 6 
#define W 21 
using namespace std;
//B[i][j]:i代表还有几件商品可以偷
//		  j代表还剩下的背包空间是多少 
int B[N][W] = {0};
int w[6] = {0, 2, 3, 4, 5, 9};//重量 
int v[6] = {0, 3, 4, 5, 8, 10};//价值

void beibao(){
	int k, c;
	for(k=1; k<N; k++){//5个商品 
		for(c=1; c<W; c++){
			if(w[k]>c){//第k件商品太重超过了背包空间c,不偷 
				B[k][c] = B[k-1][c];
			}else{
				//偷第k件商品 
				int value1 = B[k-1][c-w[k]] + v[k];
				//不偷第k件商品 
				int value2 = B[k-1][c];
				B[k][c] = value1 >= value2 ? value1:value2;
			} 
		}
	}
}

int main(void){
	beibao();
	cout << B[5][20] << endl;
	return 0;
} 

Guess you like

Origin www.cnblogs.com/Whgy/p/12301413.html