【问题标题】:Hackerearth Question: Monk and the Magical Candy BagsHackerearth 问题:和尚和魔法糖果袋
【发布时间】:2020-08-30 00:36:56
【问题描述】:

我试图解决一个关于优先级队列实现的初学者问题。 https://www.hackerearth.com/practice/data-structures/trees/heapspriority-queues/practice-problems/algorithm/monk-and-the-magical-candy-bags/description/

但是我的解决方案在最后三个测试用例中失败了。我知道为什么。我也阅读了社论,但解决方案似乎与我的解决方案非常相似。谁能帮我弄清楚我哪里出错了?

这是我的代码。

#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;
    priority_queue<int> pq;
    for (int i = 0; i < n; i++)
        cin >> a, pq.push(a);
    ll count = 0;
    while (k--) {
        count += pq.top();
        pq.push(pq.top()/2);
        pq.pop();
    }
    cout << count << "\n";
}

int main() {
    fast;
    int t = 1;
    cin >> t;
    while (t--)
        solve();
    return 0;
}

【问题讨论】:

  • 您会很高兴听到您不需要任何人的帮助来解决这个问题,只需一个您已经拥有的工具:您的调试器!这正是调试器的用途。它一次一行地运行你的程序,并向你展示正在发生的事情。了解如何使用调试器是每个 C++ 开发人员必备的技能,没有例外。在调试器的帮助下,您应该能够快速找到此程序以及您编写的所有未来程序中的所有错误,而无需向任何人寻求帮助。您是否已经尝试过使用调试器?如果不是,为什么不呢?您的调试器向您展示了什么?
  • @SamVarshavchik 我不知道如何使用调试器。不过谢谢你的建议。你能指导我一些学习它的资源吗?
  • 不同的调试器、不同的编译器、不同的操作系统,以根本不同的方式工作。无论您使用哪种调试器,它都应该有某种文档,如果没有,总有 www.google.com,它会比在 stackoverflow.com 上完全陌生的人更好地为您找到合适的资源。

标签: c++ stl priority-queue


【解决方案1】:

priority_queue的元素类型你使用int,所以可能会导致溢出。

使用priority_queue&lt;ll&gt; 而不是priority_queue&lt;int&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多