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

16

The document describes an algorithm to solve the knapsack problem. It defines functions to find the maximum value and checks subsets. It takes input of profits, weights and capacity, and outputs the optimal subset and total profit.

Uploaded by

PARTH VYAVHARE
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)
12 views

16

The document describes an algorithm to solve the knapsack problem. It defines functions to find the maximum value and checks subsets. It takes input of profits, weights and capacity, and outputs the optimal subset and total profit.

Uploaded by

PARTH VYAVHARE
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/ 3

//slip-16

q1]

#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
void main()
{
int profit,count=0;
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))

v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;

}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);

printf("Total profit = %d\n",profit);


}
____________________________________________
q2]

#include <stdio.h>
#define NODE 4
int graph[NODE][NODE] = {
{0, 1, 0, 1},
{1, 0, 1, 1},
{0, 1, 0, 1},
{1, 1, 1, 0},
};
int path[NODE];
void displayCycle() {
printf("Cycle Found: ");
for (int i = 0; i < NODE; i++)
printf("%d ", path[i]);
printf("%d\n", path[0]);
}

int isValid(int v, int k) {

if (graph[path[k - 1]][v] == 0)
return 0;

for (int i = 0; i < k; i++)


if (path[i] == v)
return 0;
return 1;
}

int cycleFound(int k) {

if (k == NODE) {

if (graph[path[k - 1]][path[0]] == 1)
return 1;
else
return 0;
}

for (int v = 1; v < NODE; v++) {


if (isValid(v, k)) {
path[k] = v;
if (cycleFound(k + 1) == 1)
return 1;

path[k] = -1;
}
}
return 0;
}

int hamiltonianCycle() {
for (int i = 0; i < NODE; i++)
path[i] = -1;

path[0] = 0;
if (cycleFound(1) == 0) {
printf("Solution does not exist\n");
return 0;
}
displayCycle();
return 1;
}
int main() {
hamiltonianCycle();
return 0;
}

You might also like