“#include <bits/stdc++.h>
using namespace std;
struct Gold
{
int weight;
int value;
double unitValue;
};
bool compareUnitValue(const Gold& a, const Gold& b)
{
return a.unitValue > b.unitValue;
}
int main()
{
int N, T;
cin >> N >> T;
vector<Gold> golds(N);
for (int i = 0; i < N; ++i)
{
cin >> golds[i].weight >> golds[i].value;
golds[i].unitValue = static_cast<double>(golds[i].value) / golds[i].weight;
}
sort(golds.begin(), golds.end(), compareUnitValue);
double totalValue = 0.0;
for (const auto& gold : golds)
{
if (gold.weight <= T)
{
totalValue += gold.value;
T -= gold.weight;
}
else
{
totalValue += gold.unitValue * T;
break;
}
}
cout << fixed << setprecision(2) << totalValue << endl;
return 0;
} ”```cpp
#include <bits/stdc++.h>
using namespace std;
struct Gold
{
int weight;
int value;
double unitValue;
};
bool compareUnitValue(const Gold& a, const Gold& b)
{
return a.unitValue > b.unitValue;
}
int main()
{
int N, T;
cin >> N >> T;
vector<Gold> golds(N);
for (int i = 0; i < N; ++i)
{
cin >> golds[i].weight >> golds[i].value;
golds[i].unitValue = static_cast<double>(golds[i].value) / golds[i].weight;
}
sort(golds.begin(), golds.end(), compareUnitValue);
double totalValue = 0.0;
for (const auto& gold : golds)
{
if (gold.weight <= T)
{
totalValue += gold.value;
T -= gold.weight;
}
else
{
totalValue += gold.unitValue * T;
break;
}
}
cout << fixed << setprecision(2) << totalValue << endl;
return 0;
}
```
by advise @ 2024-03-09 18:16:38
这是我的代码,可以参考一下```
#include <bits/stdc++.h>
using namespace std;
struct Gold
{
int weight;
int value;
double unitValue;
};
bool compareUnitValue(const Gold& a, const Gold& b)
{
return a.unitValue > b.unitValue;
}
int main()
{
int N, T;
cin >> N >> T;
vector<Gold> golds(N);
for (int i = 0; i < N; ++i)
{
cin >> golds[i].weight >> golds[i].value;
golds[i].unitValue = static_cast<double>(golds[i].value) / golds[i].weight;
}
sort(golds.begin(), golds.end(), compareUnitValue);
double totalValue = 0.0;
for (const auto& gold : golds)
{
if (gold.weight <= T)
{
totalValue += gold.value;
T -= gold.weight;
}
else
{
totalValue += gold.unitValue * T;
break;
}
}
cout << fixed << setprecision(2) << totalValue << endl;
return 0;
}
```
by advise @ 2024-03-09 18:18:43
谢谢
by devas__ljs @ 2024-03-16 16:17:35