链接
根据 a 和 b的差值去排序即可.
参考代码:
#include<bits/stdc++.h>
using i64 = long long;
struct node {
int a, b, diff;
};
bool cmp(node x, node y) {
return x.diff > y.diff;
}
inline int read() {
bool sym = 0; int res = 0; char ch = getchar();
while (!isdigit(ch)) sym |= (ch == '-'), ch = getchar();
while (isdigit(ch)) res = (res << 3) + (res << 1) + (ch ^ 48), ch = getchar();
return sym ? -res : res;
}
int main() {
int n = read(), k = read();
i64 ans = 0;
std::vector<node> nums(n + 1);
for (int i = 1; i <= n; i++) {
nums[i].a = read(), nums[i].b = read();
nums[i].diff = nums[i].a - nums[i].b;
}
std::sort(nums.begin() + 1, nums.end(), cmp);
for (int i = 1; i <= n - k; i++) {
ans += nums[i].a;
}
for(int i= n - k + 1; i <= n; i++) {
ans += nums[i].b;
}
printf("%lld\n", ans);
return 0;
}