鱼C论坛

 找回密码
 立即注册
查看: 289|回复: 1

为什么我写的不对

[复制链接]
发表于 2023-11-26 21:13:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. //  一般求最小值可以考虑小根堆去写
  4. int main()
  5. {
  6.     priority_queue<int,vector<int>,greater<int> >q;
  7.     int n,x;
  8.     cin>>n;
  9.     for(int i=1;i<=n;i++)
  10.     {
  11.         cin>>x;
  12.         q.push(x);

  13.     }
  14.     int res=0;
  15.     if(!q.empty())
  16.     {
  17.         int a= q.top();q.pop();
  18.         int b=q.top();q.pop();
  19.         int sum=a+b;
  20.         res+=sum;
  21.         q.push(sum);

  22.     }
  23.     cout<<res<<endl;

  24. }
复制代码

题目链接:https://www.luogu.com.cn/problem/P1090
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-11-26 21:14:01 | 显示全部楼层
你的代码中存在几个问题导致编译不通过:

1. 首先,在`priority_queue`的定义中,你没有指定堆中元素的类型。可以修改为`priority_queue<int>`来指定元素类型为整数。

2. 在for循环中,判断条件应该是`i<=n`而不是`i>x`。

3. 在for循环中,你没有读取每个数字x的输入语句。可以通过 `cin >> x;` 来读取每个数字。

4. 在最后的输出语句中,你没有指定要输出的变量res的值。可以修改为 `cout << res;` 来输出结果。

下面是修改后的代码:
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4. int main() {
  5.     priority_queue<int> q;
  6.     int n;
  7.     cin >> n;
  8.     for (int i = 1; i <= n; i++) {
  9.         int x;
  10.         cin >> x;
  11.         q.push(x);
  12.     }
  13.     int res = 0;
  14.     while (!q.empty()) {
  15.         int a = q.top(); q.pop();
  16.         if (q.empty()) {
  17.             res += a;
  18.             break;
  19.         }
  20.         int b = q.top(); q.pop();
  21.         int sum = a + b;
  22.         res += sum;
  23.         q.push(sum);
  24.     }
  25.     cout << res;
  26.     return 0;
  27. }
复制代码

希望以上回答能够帮到你!如果还有其他问题,请随时提问。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 12:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表