闲聊群里有一个初三的小哥哥,有的人觉得别人才初三,不应该叫他小弟弟吗?哈哈哈。
如果别人问的问题比较简单,那么他应该是一个弟弟。如果问的题我们解决不了那可能就得叫他哥哥了。对吧。
今天这位小“哥哥”又来问问题了。题是这样的:
有n座山,他们连在一起成一条直线,接着从左往右给出每座山的高度a[i],现在的问题是让你求的每座山右边的第一个比它高的山是第几座山呢?如果没有则输出0
Input
测试数据有多组。对于每组测试数据:
输入一个n表示有n座山(1 <= n <= 1000000)
接着输入n个数a[i] ( 1 <= a[i] <= 1000000),表示第i座山的高度。
Output
对于每组测试数据输出每座山右边的第一个比它高的山是第几座山?如果没有则输出0
Sample Input
5
1 2 3 4 5
3
1 1 1
Sample Output
2 3 4 5 0
0 0 0
维护一个单调递减栈
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
using namespace std;
int ans[1000010];
struct node {
int p;
int num;
};
int main() {
int n, i, cnt, x;
stack<node> s;
while (~scanf("%d", &n)) {
cnt = 0;
node a;
for (i = 1; i <= n; i++) {
scanf("%d", &x);
if (s.empty()) {
a.p = i;
a.num = x;
s.push(a);
continue;
}
if (x <= s.top().num) {
a.p = i;
a.num = x;
s.push(a);
}
else {
while (x > s.top().num) {
ans[s.top().p] = i;
s.pop();
if (s.empty())
break;
}
a.p = i;
a.num = x;
s.push(a);
}
}
for (i = 1; i <= n; i++) {
if (ans[i]){
printf("%d ", ans[i]);
ans[i]=0;
}
else
printf("0 ");
}
while (!s.empty())
s.pop();
printf("\n");
}
return 0;
}