戳一戳https://www.luogu.com.cn/problem/P2240
题解:
别把这题想复杂化就行
简单贪心
但可能会被卡数据
出现不管怎么改(虽然确实可能是对的)但结果总是有一个会wa
代码中有详细注释
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node {//定义结构体
double w;//重量
double v;//价值
double p;//性价比
}a[105];
int n;
double sum, c;
bool cmp(node a, node b) {
return a.p > b.p;//性价比从大到小排序
}
int main() {
cin >> n >> c;
for (register int i = 1; i <= n; ++i) {
cin >> a[i].w >> a[i].v;
a[i].p = a[i].v / a[i].w;//性价比=价格/重量
}
sort(a + 1, a + n + 1, cmp);//将性价比排序
for (int i = 1; i <= n; ++i) {
if (c >= a[i].w) {//金币的重量小于或等于背包的承重量
c -= a[i].w;//装上该堆金币后背包的剩余承重量
sum += a[i].v;//金币的价值
}
else {
sum += c * a[i].p;//如果装不下就分割金币
break;
}
}
printf("%.2f", sum);//保留小数点后两位输出
return 0;
}