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

Knapsack

The document contains a C program that implements the fractional knapsack problem. It calculates the maximum profit that can be obtained given a set of objects with specific weights and profits, and a knapsack with a defined capacity. The program sorts the objects based on their profit-to-weight ratio and determines the optimal selection of items to maximize profit.
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)
6 views2 pages

Knapsack

The document contains a C program that implements the fractional knapsack problem. It calculates the maximum profit that can be obtained given a set of objects with specific weights and profits, and a knapsack with a defined capacity. The program sorts the objects based on their profit-to-weight ratio and determines the optimal selection of items to maximize profit.
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 knapsack(int n, float w[], float p[], float capacity)


{
float a[20], tp = 0;
int i, j, u;
u = capacity;

for (i = 0; i < n; i++)


a[i] = 0.0;

for (i = 0; i < n; i++)


{
if (w[i] > u)
break;
else {
a[i] = 1.0;
tp = tp + p[i];
u = u - w[i];
}
}

if (i < n)
a[i] = u / w[i];

tp = tp + (a[i] * p[i]);

printf("\nThe result vector is:- ");


for (i = 0; i < n; i++)
printf("%f\t", a[i]);

printf("\nMaximum profit is:- %f", tp);

int main()
{
float w[20], p[20], capacity;
int n, i, j;
float r[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &n);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < n; i++) {
scanf("%f %f", &w[i], &p[i]);
}

printf("\nEnter the capacity of knapsack:- ");


scanf("%f", &capacity);

for (i = 0; i < n; i++) {


r[i] = p[i] / w[i];
}

for (i = 0; i < n; i++) {


for (j = i + 1; j < n; j++) {
if (r[i] < r[j]) {
temp = r[j];
r[j] = r[i];
r[i] = temp;

temp = w[j];
w[j] = w[i];
w[i] = temp;

temp = p[j];
p[j] = p[i];
p[i] = temp;
}
}
}

knapsack(n, w, p, capacity);
return(0);
}

You might also like