know the personalities
hold your mouse,move left and right

Subset Sum Problem


#include<stdio.h>
#include<conio.h>
void subset(int,int,int);
int m,r1,x[25],k,r=0,s=0,w[25],i,n;
void main()
{
clrscr();
printf("\n\nSubset Sum Problem\n\n");
printf("\n\tEnter the maximum number of elements :");
scanf("%d",&n);
for(i=0;i<n;i++)
x[i] = 0;
for(i=0;i<n;i++)
{
printf("\n Enter the [%d] element ",i+1);
scanf("%d",&w[i]);
r=r+ w[i];
}
//r1 = r
printf("\n\tEnter the Sum :");
scanf("%d",&m);
subset(0,0,r);
getch();
}
void subset(int s,int k,int r)
{
x[k]=1;
if(s+w[k]==m)
{
printf("\nSolutions :");
for(i=0;i<n;i++)
{
if(x[i])
printf("\t%d",w[i]);
}
for(i=k+1;i<n;i++)
x[i]=0;
getch();
//r = r1;
}
else if(s+w[k]+w[k+1]<=m)
subset(s+w[k],k+1,r-w[k]);
if(s+r-w[k]>=m && s+w[k+1]<=m)
{
x[k]=0;
subset(s,k+1,r-w[k]);
}
}

More Lab Programs with Answers -Given Below-Click and Get Freely

Hosting by Yahoo!

About-Us    Contact-Us    Site-map

©copyright 2009 All rights are reserved to technicalsymposium.com