10CSL47
Design and Analysis of Algorithms Laboratory
8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S={1, 2, 5, 6, 8} and d = 9 there are two
solutions{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't
have a solution.
Program
#include<iostream.h>
#include<conio.h>
#include<math.h>
void sumofsub(int num,int n,int x[])
{
int i;
for(i=1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i]=num%2;
num=num/2;
}
}
void main()
{
int a[20],x[20],n,j,i,d,sum,present=0;
clrscr();
cout<<"Enter the number of Elements:";
cin>>n;
cout<<"\nEnter the Elements in Ascending Order:";
for(i=1;i<=n;i++)
cin>>a[i];
cout<<"\nEnter the Sum value:";
cin>>d;
for(i=1;i<=pow(2,n)-1;i++)
{
sumofsub(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum=sum+a[j];
if(d==sum)
{
cout<<"\nSubset={";
Prashanth Kumar
CSE DEPT, VVCE, Mysore
10CSL47
Design and Analysis of Algorithms Laboratory
present=1;
for(j=1;j<=n;j++)
if(x[j]==1)
cout<<a[j];
cout<<"}="<<d;
}
}
if(present==0)
cout<<"\nSolution doesn't Exist";
getch();
}
/*************************************OUTPUT***************************************/
Enter the number of Elements: 5
Enter the Elements in Ascending Order: 1 2 5 6 8
Enter the Sum value: 9
Subset= {18} = 9
Subset= {126} =9
Prashanth Kumar
CSE DEPT, VVCE, Mysore