贪心算法货郎问题c++
时间: 2024-01-04 07:18:23 浏览: 91
以下是贪心算法货郎问题的C++代码实现:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10010;
struct Goods {
int w, v;
double p;
} goods[N];
bool cmp(Goods a, Goods b) {
return a.p > b.p;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> goods[i].w >> goods[i].v;
goods[i].p = 1.0 * goods[i].v / goods[i].w;
}
sort(goods, goods + n, cmp);
double ans = 0;
for (int i = 0; i < n; i++) {
if (m >= goods[i].w) {
ans += goods[i].v;
m -= goods[i].w;
} else {
ans += m * goods[i].p;
break;
}
}
printf("%.2lf\n", ans);
return 0;
}
```
阅读全文