这道题就是动态规划(DP),将 “酸度和甜度相等” 转化为 “酸度 - 甜度 = 0”,用 DP 数组记录「酸度 - 甜度差值」对应的「酸度 + 甜度总和」的最大值,最终找差值为 0 时的最大总和就行了
下面贴上我的代码:
#include <bits/stdc++.h>
using namespace std;
const int O = 50000;
const int s = 100001; // DP数组总长度
int main(){
int n;
cin >> n;
int dp[s]; // dp[j]:差值为(j-O)时,酸甜总和的最大值
memset(dp, -1, sizeof(dp)); // 初始化-1表示该差值状态不可达
dp[O] = 0;
for (int i = 1; i <= n; i++){ // 遍历食材
int a, b;
cin >> a >> b;
int d = a - b; // 差值
int t = a + b; // 总和
int tmp[s];
memcpy(tmp, dp, sizeof(dp)); // 复制当前DP,避免覆盖
// 遍历
for (int j = 0; j < s; j++){
if (tmp[j] == -1) continue; // 跳过不可达的状态
int nj = j + d; // 选当前食材后的新差值位置
if (nj < 0 || nj >= s) continue; // 超出数组范围则跳过
// 更新新差值状态的最大总和
if (tmp[j] + t > dp[nj]) dp[nj] = tmp[j] + t;
}
}
// 差值为0(对应dp[O])时的总和,不可达则输出0
int ans = (dp[O] == -1) ? 0 : dp[O];
cout << ans << endl;
return 0;
}可读性+1