top k 问题, 通过排序可以解决问题, 只不过题目要求如果有多种方案, 希望总酸度尽可能小. 那么可以使用 sort 并自定义排序规则, 让甜度大的往前排, 甜度相同但酸度小的往前排, 可以升序也可以降序, 后边遍历求和时注意顺序即可, 题解代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<pair<long, long>> arr(n);
//输入酸度
for(int i = 0; i < n; ++i)
{
cin >> arr[i].first;
}
//输入甜度
for(int i = 0; i < n; ++i)
{
cin >> arr[i].second;
}
sort(arr.begin(), arr.end(), [&](const pair<long, long>& p1, const pair<long, long>& p2){
if(p1.second == p2.second)
{
return p1.first > p2.first;
}
return p1.second < p2.second;
});
long acid = 0, sweet = 0;
for(int i = arr.size() - 1; i >= n - k; --i)
{
acid += arr[i].first;
sweet += arr[i].second;
}
cout << acid << " " << sweet << endl;
return 0;
}