0% found this document useful (0 votes)
35 views1 page

Implimentation of Greedy Algo Knapsack Probl

The document contains a C++ implementation of the fractional knapsack problem using a greedy algorithm. It defines a structure for items with value and weight, sorts them based on their value-to-weight ratio, and calculates the maximum value that can be carried in a knapsack of a given capacity. The main function demonstrates the algorithm with a sample input of items and knapsack capacity.

Uploaded by

Sunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views1 page

Implimentation of Greedy Algo Knapsack Probl

The document contains a C++ implementation of the fractional knapsack problem using a greedy algorithm. It defines a structure for items with value and weight, sorts them based on their value-to-weight ratio, and calculates the maximum value that can be carried in a knapsack of a given capacity. The main function demonstrates the algorithm with a sample input of items and knapsack capacity.

Uploaded by

Sunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <bits/stdc++.

h>
using namespace std;

struct Item {
int value, weight;

Item(int value, int weight)


{
this->value = value;
this->weight = weight;
}
};
bool cmp(struct Item a, struct Item b)
{
double r1 = (double)[Link] / (double)[Link];
double r2 = (double)[Link] / (double)[Link];
return r1 > r2;
}

double fractionalKnapsack(int W, struct Item arr[], int N)


{
sort(arr, arr + N, cmp);

double finalvalue = 0.0;

for (int i = 0; i < N; i++) {

if (arr[i].weight <= W) {
W -= arr[i].weight;
finalvalue += arr[i].value;
}

else {
finalvalue
+= arr[i].value
* ((double)W / (double)arr[i].weight);
break;
}
}
return finalvalue;
}

int main()
{
int W = 50;
Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };

int N = sizeof(arr) / sizeof(arr[0]);

cout << fractionalKnapsack(W, arr, N);


return 0;
}

You might also like