先假设全部巧克力都在白天吃完,然后在根据晚上的甜蜜值与白天的甜蜜值的差距从大到小排序替换掉 n - k 个白天时吃的巧克力。注意要开long long。
#include <bits/stdc++.h> using namespace std; struct sweetness { int day, night; }tmp; bool cmp(sweetness a, sweetness b) { return a.night - a.day > b.night - b.day; } int main() { int n, k; long long ans = 0; cin >> n >> k; vector <sweetness> v; for (int i = 0; i < n; i++) { cin >> tmp.day; tmp.night = 0; v.push_back(tmp); ans += tmp.day; } for (int i = 0; i < n; i++) { cin >> v[i].night; } sort(v.begin(), v.end(), cmp); for (int i = 0; i < n - k; i++) { ans += v[i].night - v[i].day; } cout << ans; }