-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubset.cpp
More file actions
64 lines (64 loc) · 1.11 KB
/
subset.cpp
File metadata and controls
64 lines (64 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*tenth program*/
#include<stdio.h>
#include<conio.h>
#define m 30
void subset(int n,int d,int s[]);
void main()
{
int i,n,d,s[m];
clrscr();
printf("\nEnter number of elements : ");
scanf("%d",&n);
printf("\nEnter the set in increasing order\n");
for(i=0;i<n;i++)
scanf("%d",&s[i]);
printf("\nEnter the sum of subset d = ");
scanf("%d",&d);
subset(n,d,s);
getch();
}
void subset(int n,int d,int s[])
{
int i,k,sum=0,selected[m],found=0;
for(i=0;i<n;i++)
selected[i]=0;
k=0;
selected[k]=1;
while(1)
{
if(k<n && selected[k]==1)
{
if(sum+s[k]==d)
{
found=1;
printf("\n\nSolution is : \n\n");
for(i=0;i<n;i++)
{
if(selected[i]==1)
printf("%d\t",s[i]);
}
selected[k]=0;
}
else if(sum+s[k]<d)
sum+=s[k];
else
selected[k]=0;
}
else
{
k--;
while(k>=0 && selected[k]==0)
{
k--;
}
if(k<0)
break;
selected[k]=0;
sum-=s[k];
}
k++;
selected[k]=1;
}
if(!found)
printf("\nSolution does not exist");
}