01 knapsack problem (dfs + pruning)

01 knapsack problem

dfs Solution

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <cmath>
 5 
 6 using namespace std ;
 7     
 8 const int N = 1010 ;
 9 
10 int v[N],w[N] ;
11 int n,V ;
12 int ans = 0 ;
13 
14 void dfs(int idx,int h,int m){
15     if(idx == n){
16         return ;
 . 17      }
 18 is      DFS (+ IDX . 1 , H, m); // not a first branch represents the current selected item
 . 19      IF (H + V [IDX] <= V) {// Only the current equal to the current capacity greater than the article knapsack volume, before entering the second branch
 20 is          IF (ANS <m + W [IDX]) {
 21 is              ANS = m + W [IDX];
 22 is          }
 23 is          DFS (IDX + . 1 , H + V [IDX], m + W [IDX] );
 24      }
 25  }
 26 is  
27  int main () {
 28      CIN >> >> n- V;
 29      
30      for ( int I = 0;i<n;i++){
31         cin >> v[i] ;
32     }
33     for(int i=0;i<n;i++){
34         cin >> w[i] ;
35     }
36     
37     dfs(0,0,0) ;
38     
39     cout << ans << endl ;
40     
41     return 0 ;    
42 } 

 

...

Guess you like

Origin www.cnblogs.com/gulangyuzzz/p/12056152.html