You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Monk与魔法糖果袋代码最后三组测试用例失败排查

问题分析与解决方案

我一眼就发现了导致你代码在最后几组测试用例失败的核心问题——优先队列的类型不匹配,这是竞赛题里很容易踩的数值溢出坑。

问题根源

你定义的优先队列是 priority_queue<int> pq,但输入的糖果数量变量 a 是 long long 类型。当题目中的测试用例包含超过 int 范围的数值时(比如大于 (2^{31}-1) 的数),将这些大数值强制塞进 int 类型的队列会触发整数溢出,导致数值被错误截断,后续的取最大值、分割计算都会完全偏离正确结果。

修正后的代码

只需要把优先队列的类型改成 long long 即可解决问题,以下是调整后的完整代码:

#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0); cin.tie(0);
#define ll long long
#define pb push_back
#define mp make_pair
#define all(x) x.begin(), x.end()
#define ff first
#define ss second
#define foreach(it, v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end(); it++)
#define MOD 1000000007
#define dbg(x) { cout<< #x << ": " << (x) << endl; }
#define dbg2(x,y) { cout<< #x << ": " << (x) << " , " << #y << ": " << (y) << endl; }
/* __builtin_popcount(), __builtin_popcountll() // return no. of set bits
next_permutation(v.begin(), v.end()) */
void solve() {
 int n, k;
 cin >> n >> k;
 ll a;
 // 把int改成ll,匹配输入的数值类型
 priority_queue<ll> pq;
 for (int i = 0; i < n; i++) {
     cin >> a;
     pq.push(a);
 }
 ll count = 0;
 while (k--) {
     ll top_val = pq.top();
     count += top_val;
     pq.push(top_val / 2);
     pq.pop();
 }
 cout << count << "\n";
}
int main() {
 fast;
 int t = 1;
 cin >> t;
 while (t--) solve();
 return 0;
}

额外优化小提示

我还帮你把每次取的队首值存到了一个ll变量里,避免重复调用pq.top(),虽然这不是必须的,但能让代码更清晰,也减少了一点点重复操作的开销。

内容的提问来源于stack exchange,提问作者Roopam Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:23:13