我的同学作的
背包法解决求和问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YES 1
#define NO 0
#define NOT_FOUND -1
void reverse(int [],int);
int knapsack(int size[],int n,int SIZE,int result[])
{
int **exist;
int **member;
int count;
int i,j;
exist=(int **)malloc(sizeof(int *)*(n+1));
exist[0]=(int *)malloc(sizeof(int)*(n+1)*(SIZE+1));
member=(int **)malloc(sizeof(int *)*(n+1));
member[0]=(int *)malloc(sizeof(int)*(n+1)*(SIZE+1));
for(i=1;i<=n;i++)
{
exist[i]=exist[i-1]+(SIZE+1);
member[i]=member[i-1]+(SIZE+1);
}
exist[0][0]=YES;
for(j=1;j<=SIZE;j++)
exist[0][j]=NO;
for(i=1;i<=n;i++)
for(j=0;j<=SIZE;j++)
{
exist[i][j]=member[i][j]=NO;
if(exist[i-1][j])
{
exist[i][j]=YES;
member[i][j]=NO;
}
else if(j>=size[i-1])
if(exist[i-1][j-size[i-1]])
{
exist[i][j]=YES;
member[i][j]=YES;
}
}
if(exist[n][SIZE])
{
for(count=0,i=n,j=SIZE;i!=0&&j!=0;)
if(member[i][j]==YES)
{
result[count++]=--i;
j-=size[i];
}
else
{
i--;
}
reverse(result,count);
}
else
count=NOT_FOUND;
return count;
}
#define SWAP(a,b) {temp=a;a=b;b=temp;}
void reverse(int x[],int n)
{
int i,j,temp;
for(i=0,j=n-1;i<j;i++,j--)
SWAP(x[i],x[j]);
}
int main(void)
{
int i,j,n,m,num1[1000],num2[1000];
int a,b,p;
int knapsack(int size[],int n,int SIZE,int result[]);
scanf("%d",&n);
while(n--)
{
scanf("%d %d",&a,&b);
for(i=0;i<a;i++)
{
scanf("%d",&num1[i]);
}
p=knapsack(num1,a,b,num2);
if(p>=0)
printf("yes\n");
else
printf("no\n");
}
return 0;
}