0% found this document useful (0 votes)
31 views

Sum of Subsets Using Back Viva

This document describes a backtracking algorithm to find all subsets of a set of weights that sum to a target value. It takes in the number of objects, their individual weights, and a target sum. It then sorts the weights in ascending order and uses a recursive backtracking function to try all combinations of including or excluding each weight from the subset. Any subsets found that equal the target sum are printed out.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Sum of Subsets Using Back Viva

This document describes a backtracking algorithm to find all subsets of a set of weights that sum to a target value. It takes in the number of objects, their individual weights, and a target sum. It then sorts the weights in ascending order and uses a recursive backtracking function to try all combinations of including or excluding each weight from the subset. Any subsets found that equal the target sum are printed out.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

SUM OF SUBSETS USING BACK-TRACKING METHODS

#include<stdio.h>
#include<conio.h>
int w[25];
void sos(s,k,r,m)
{
int i;
static int x[25];
x[k]=1;
if(s+w[k]==m)
{
printf("\n\n\t THE SUBSET ");
printf(" { ");
for(i=1;i<=k;i++)
{
printf("%d ",x[i]);
}
printf(" } ");
}
else
if((s+w[k]+w[k+1])<=m)
{
sos(s+w[k],k+1,r-w[k],m);
}
if(((s+r-w[k])>=m)&&(s+w[k+1])<=m)
{
x[k]=0;
sos(s,k+1,r-w[k],m);
}
}
void main()
{
int i,j,sm,n,sum=0,r,max,temp;
clrscr();

printf("\n\t\t\t *-*-*-* SUM OF SUBSET *-*-*-* \n");


printf("\n\t ENTER THE NUMBER OF OBJECT : ");
scanf("%d",&n);
printf("\n\t ENTER THE WEIGHT OF THE OBJECT : ");
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
sum +=w[i];
}
printf("\n\n ENTER THE WEIGHT OF THE FINDING OBJECTS : ");
scanf("%d",&sm);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(w[i]<w[j])
{
temp=w[i];
w[i]=w[j];
w[j]=temp;
}
}
}
if(sm<w[i])
{
printf("\n\n SUMBSET CAN'T BE FOUND ");
}
else
{
printf("\n\n GIVEN SET : ");
printf(" { ");
for(i=1;i<=n;i++)
{
printf("%d ",w[i]);
}

printf(" } ");
printf("\n\n SUBSET FORMED WITH AS %d ",sm);
sos(0,1,sum,sm);
}
getch();
}

OUTPUT:

*-*-*-* SUM OF SUBSET *-*-*-*


ENTER THE NUMBER OF OBJECT : 5
ENTER THE WEIGHT OF THE OBJECT : 5 10 15 20 25
ENTER THE WEIGHT OF THE FINDING OBJECTS : 35
GIVEN SET : { 5 10 15 20 25 }
SUBSET FORMED WITH AS 35
THE SUBSET { 1 1 0 1 }
THE SUBSET { 0 1 0 0 1 }
THE SUBSET { 0 0 1 1 }

You might also like