为什么我用于打印堆栈中最大元素的C++代码没有产生正确的输出



我正在进行编程练习最大元素(https://www.hackerrank.com/challenges/maximum-element/problem?isFullScreen=false)使用C++,练习的目标是为每个类型3查询打印最大元素。每个查询都是以下三种类型之一:

  1. 将元素x推入堆栈。

  2. 删除堆栈顶部的元素。

  3. 打印堆栈中的最大元素。

对于输入:

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

预期输出为:

26
91

我的代码正在打印:

0
0

我的代码(写在下面(显然打印了错误的答案,但我找不出我在哪里犯了错误。我如何解释这个问题,或者调试我的错误?

#include<iostream>
#include<stack>
using namespace std;
int main() {
int n;
cin>>n;
while(n--)
{
stack<int> s;
int a;
cin>>a;
if(a==1)
{
int x;
cin>>x;
s.push(x);
}
else if (a==2)
s.pop();
else {
int max =0;
while(!s.empty())
{
if(s.top()>max)
max=s.top();
s.pop();
}
cout<<max<<endl;
}
}   
return 0;
}

您在循环内部声明了堆栈stack<int> s;,因此它将在循环的每一个开始都被清除。声明应该在类似的循环之外

stack<int> s; // move here, for example
int n;
cin>>n;
while(n--)
{
// stack<int> s;

这个更改将使这里的输入输出正确,但我认为只有这个更改程序是不正确的。我认为类型3查询不应该删除堆栈中的元素。

1(声明堆栈退出循环2( 之前,元素被弹出以寻找最大元素,因此制作了另一个堆栈来跟踪最大元素

新代码通过了所有测试用例:-

#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s, max;
max.push(0);
int n;
cin >> n;
while (n--) {
int a;
cin >> a;
if (a == 1) {
int x;
cin >> x;
s.push(x);
if (x >= max.top())
max.push(x);
} else if (a == 2) {
int q = s.top();
if (q == max.top())
max.pop();
s.pop();
} else {
cout << max.top() << endl;
}
}
return 0;
}

您在循环中声明了堆栈,在这种情况下,每次递增或递减都会将值设置回初始状态。

一个快速的解决方案是在循环之外声明堆栈,剩下的代码看起来很好。

最新更新