Skip to content

Instantly share code, notes, and snippets.

@Neo-sunny
Created September 2, 2019 12:57
Show Gist options
  • Save Neo-sunny/9bed04628641b411263212f806085362 to your computer and use it in GitHub Desktop.
Save Neo-sunny/9bed04628641b411263212f806085362 to your computer and use it in GitHub Desktop.
// C/C++ program to solve greedy mobile Manuf.
#include <bits/stdc++.h>
using namespace std;
// Structure for an Mobile which stores Parts manf. and Assembling
struct Mobile
{
int pm, assm;
// Constructor
Mobile(int pm, int assm) : pm(pm), assm(assm)
{}
};
// Comparison function to sort Item according to val/weight ratio
bool cmp(struct Mobile a, struct Mobile b)
{
double r1 = (double)a.pm / a.assm;
double r2 = (double)b.pm / b.assm;
return r1 < r2;
}
// Main greedy function to solve problem
void Greedy4MobProd( struct Mobile arr[], int n)
{
// sorting Item on basis of ratio
sort(arr, arr + n,cmp);
for (int i = 0; i < n; i++)
{
cout << arr[i].pm << " " << arr[i].assm << " : "
<< ((double)arr[i].pm / arr[i].assm) << endl;
}
}
// driver program to test above function
int main()
{
int W = 50; // Weight of knapsack
Mobile arr[] = {{5,7}, {1, 2}, {8,2},{5,4}};
int n = sizeof(arr) / sizeof(arr[0]);
Greedy4MobProd(arr, n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment