我必须为最好的第一个分支和绑定背包问题实现一个算法。但是,我的算法没有给我正确的答案。我的KWF2功能找出上限工作,但调用背包(0,0,0,n)给了我一个非常不正确的答案5,当它应该是90。
#include <stdio.h>
#include <stdlib.h>
int C;
int *w;
int *p;
int maxprofit;
int *include;
int *bestset;
float *x;
int numbest;
void knapsack(int i, int weight, int profit, int n);
int promising(int i, int weight, int profit, int n);
int KWF2(int i, int weight, int profit, int n);
int main(int argc, char **argv){
FILE *in = fopen(argv[1],"r");
int n;
fscanf(in,"%d,%d\n",&n,&C);
//scan in items
w = malloc(sizeof(int)*(n+1));
p = malloc(sizeof(int)*(n+1));
include = malloc(sizeof(int)*(n+1));
bestset = malloc(sizeof(int)*(n+1));
x = malloc(sizeof(float) * (n+1));
float ratio[n+1];
int i;
for(i = 0; i < n; i++){
fscanf(in,"%d,%d\n",&w[i+1],&p[i+1]);
ratio[i+1] = (float)p[i+1] / (float)w[i+1];
}
//sort in decreasing p/w ratio
int temp_w,temp_p;
float temp_r;
int j;
for(i = 1; i <= n; i++){
for(j = i + 1; j <= n; j++){
if(ratio[i] < ratio[j]){
temp_w = w[i];
temp_p = p[i];
temp_r = ratio[i];
w[i] = w[j];
p[i] = p[j];
ratio[i] = ratio[j];
w[j] = temp_w;
p[j] = temp_p;
ratio[j] = temp_r;
}
}
}
//printf("bound of 1 = %d",KWF2(1,2,40,n));
maxprofit = 0;
numbest = 0;
//printf("node 2 bound = %d\n",KWF2(2,2,40,n));
knapsack(0,0,0,n);
//printf("maxprofit = %d\n",maxprofit);
fclose(in);
return 0;
}
void knapsack(int i, int weight, int profit, int n){
printf("profit= %d\n",profit);
if(weight <= C && profit > maxprofit){
maxprofit = profit;
numbest = i;
int j;
for(j = 0; j <= n; j++){
bestset[i] = include[i];
}
}
if(promising(i,weight,profit,n)){
include[i+1] = 1;
knapsack(i+1,profit+p[i+1],weight + w[i+1],n);
include[i+1] = 0;
knapsack(i+1,profit,weight, n);
}
}
int promising(int i, int weight, int profit, int n){
if(weight >= C) return 0;
int bound = KWF2(i+1,weight,profit,n);
//printf("bound = %d\n",bound);
if(bound > maxprofit) {
//printf("bound = %d\n",bound);
return 1;
}
else return 0;
}
int KWF2(int i, int weight, int profit, int n){
int weight1 = weight;
int bound = profit;
int j;
for(j = i; j <= n; j++){
x[j] = 0;
}
while(weight1 < C && (i <= n)){
if(weight1 + w[i] <= C){
x[i] = 1;
weight1 += w[i];
bound += p[i];
}
else{
x[i] = ((float)C-(float)weight1)/(float)w[i];
weight1 = C;
bound = bound + p[i] * x[i];
}
i++;
}
//printf("profit = %d\n",profit);
//printf("%d\n",profit+p[2]+(C-7)*p[3]/w[3]);
return bound;
}