0% found this document useful (0 votes)
3 views2 pages

Subset

The document contains a C program that calculates subsets of weights that sum to a specified value. It prompts the user for the number of weights, their values, and the required subset sum, then uses a recursive function to find and display valid subsets. If no valid subsets exist, it informs the user that the total sum of weights is less than the required sum.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Subset

The document contains a C program that calculates subsets of weights that sum to a specified value. It prompts the user for the number of weights, their values, and the required subset sum, then uses a recursive function to find and display valid subsets. If no valid subsets exist, it informs the user that the total sum of weights is less than the required sum.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<stdio.

h>
void SumOfSub(int,int,int);
int x[25],n,m=0,sum=0,w[25];;
void readf()
{
int i;
printf("\n Enter the no of values in the set:");
scanf("%d",&n);
printf("\n Enter the %d weights of the values in the set:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
sum=sum+w[i];
x[i]=0;
}
printf("\n Enter the required sum of the values in the subset:");
scanf("%d",&m);
printf("\n The Total sum of the weights is:%d",sum);
SumOfSub(0,1,sum);
}
void SumOfSub(int s,int k,int r)
{
int i;
x[k]=1;
if(sum>=m)
{
if(s+w[k]==m)
{
printf("\n");
for(i=1;i<=n;i++)
{
printf("%d\t",x[i]);
}
printf("\n-->");
for(i=1;i<=k;i++)
{
if(x[i] == 1)
printf("%d\t",w[i]);
}
x[k]=0;
printf("\n");
}
else if(s+w[k]+w[k+1]<=m)
SumOfSub(s+w[k],k+1,r-w[k]);
if((s+r-w[k]>=m) && (s+w[k+1]<=m))
{
x[k]=0;
SumOfSub(s,k+1,r-w[k]);
}
}
else
{
printf("\n No Solutions Available because sum of all weights is %d less
than required sum%d",sum,m);
}
}
int main()
{
readf();

You might also like