NSUOJ 2586 弟弟or哥哥

闲聊群里有一个初三的小哥哥,有的人觉得别人才初三,不应该叫他小弟弟吗?哈哈哈。

如果别人问的问题比较简单,那么他应该是一个弟弟。如果问的题我们解决不了那可能就得叫他哥哥了。对吧。

今天这位小“哥哥”又来问问题了。题是这样的:

有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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值