关于简化背包问题的算法源代码

#include<stdio.h>
#include<stdlib.h>

int knap(int s, int n, int w[]) {
if ( s == 0 )
return (1);
else if ( s<0 || s>0 && n<1 )
return(0);
else if ( knap(s - w[n-1], n - 1, w)==1 ) {
printf("result: w[%d]=%d \n", n-1, w[n-1]);
return (1);
}
else
return ( knap(s, n - 1, w) );
}

void main() {
int* w;
int s = 0, n = 0, i = 0;
printf("please input t = ");/*输入s*/
scanf("%d", &s);
printf("please input n = ");/*输入n*/
scanf("%d", &n);
w = (int*)malloc(n*sizeof(int));
printf("please input the %d numbers(weight):\n", n);/*输入重量*/
for (i = 0; i < n; i++)
scanf("%d", w+i);
while(n)
{knap(s, n, w); n--;
printf("\n");
}
}

Copyright © 2007-2012 www.chuibin.com 六维论文网 版权所有