01背包问题-回溯法
#include <stdio .h> #include <stdlib .h> int n=5,c=10; int value[5]={6,3,5,4,6}; int weight[5]={2,2,6,5,4}; int cv[5]={0,0,0,0,0}; int bv[5]={0,0,0,0,0}; int cw=0; int curv = 0 ; int bestv =0 ; void output() { int i =0; for(i; i<n ; i++) printf("%d ",bv[i]); printf("%d",bestv); } void trackback(int i) { int j; if(i>=n) { if(bestv<curv ) { for(j=0;j<n;j++) bv[j] = cv[j]; bestv = curv; } } else { if(cw + weight[i]<=c) { cv[i] = 1; cw +=weight[i]; curv+= value[i]; trackback(i+1); cw -=weight[i]; curv-= value[i]; } cv[i] =0; trackback(i+1); } } int main(int argc, char *argv[]) { trackback(0); output(); system("PAUSE"); return 0; }