C语言数据结构 背包问题
#include<stdio.h>#include<stdlib.h>intknap(ints,intn,intw[]){if(s==0)return1;elseif((...
#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: n=%d ,w[%d]=%d\n", n, n-1, w[n-1]);
return 1;
}
else
return ( knap(s, n - 1, w) );
}
int main()
{
int* w;
int s = 0, n = 0, result = 0, i = 0;
printf("please input s = ");/*输入s*/
scanf("%d", &s);
printf("please input n = ");/*输入n*/
scanf("%d", &n);
w = (int*)malloc(n*sizeof(int));
v = (int*)malloc(n*sizeof(int));
printf("please input the %d numbers(weight):\n", n);/*输入重量*/
for (i = 0; i < n; i++)
scanf("%d", w+i);
result = knap(s, n, w);
if (result == 0)
printf("no solution!\n");
return 0;
}
这是一个0-1背包问题的代码。我想在中间加一个价值变量。求背包内装满并且价值最高。要怎么改? 展开
#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: n=%d ,w[%d]=%d\n", n, n-1, w[n-1]);
return 1;
}
else
return ( knap(s, n - 1, w) );
}
int main()
{
int* w;
int s = 0, n = 0, result = 0, i = 0;
printf("please input s = ");/*输入s*/
scanf("%d", &s);
printf("please input n = ");/*输入n*/
scanf("%d", &n);
w = (int*)malloc(n*sizeof(int));
v = (int*)malloc(n*sizeof(int));
printf("please input the %d numbers(weight):\n", n);/*输入重量*/
for (i = 0; i < n; i++)
scanf("%d", w+i);
result = knap(s, n, w);
if (result == 0)
printf("no solution!\n");
return 0;
}
这是一个0-1背包问题的代码。我想在中间加一个价值变量。求背包内装满并且价值最高。要怎么改? 展开
3个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询