【发布时间】:2019-11-29 14:11:04
【问题描述】:
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
stack<int>s;
stack<int>q;
for (int i = n - 1; i > 0; i--)
{
s.push(arr[i]);
}
while (!s.empty())
{
int a = s.top();
s.pop();
int flag = 0;
while (!s.empty())
{
int p = s.top();
if (a >= p)
{
q.push(p);
s.pop();
}
else {
cout << p;
flag = 1;
break;
}
p = s.top();
}
if (flag == 0)
{
cout << -1;
}
while (!q.empty())
{
s.push(q.top());
q.pop();
}
}
}
return 0;
}
给定一个数组,打印每个元素的下一个更大元素 (NGE)。元素 x 的下一个更大元素是数组中 x 右侧的第一个更大元素。对于不存在更大元素的元素,将下一个更大元素视为-1。 为什么这段代码会出现分段错误?
【问题讨论】:
-
可能不相关。
int n; cin>>n; int arr[n];不是合法的 C++。在 C++ 中数组边界必须是编译时常量,但在上面的代码中n是一个变量。 -
将
int arr[n];替换为vector<int> arr(n);,这至少是合法的C++ 并且可能会解决问题。 -
@J.Soumya 为什么要使用堆栈?只使用循环会更简单吗?
-
什么是
#include<bits/stdc++.h>?它不是标准标题 -
我猜使用循环会花费更多时间。