SPOJ - Fata7y Ya Warda! - 单调栈

Fata7y Ya Warda!

题目链接

分类:单调栈

1.题意概述

  • 给你一个环编号从1到n且1与n相邻,询问每个点的左右侧最近的严格比它小的第一个数编号,如果没有则输出-1

2.解题思路

  • 分别维护左右两边的单调栈即可,但是因为是环,注意1和n因此可以把长度沿长一倍,方便逆时针!

3.AC代码

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define maxn 100100
#define N 1111
#define eps 1e-6
#define pi acos(-1.0)
#define e exp(1.0)
using namespace std;
const int mod = 1e9 + 7;
typedef long long ll;
typedef unsigned long long ull;
deque<int> l, r;
stack <int> s;
int h[maxn];
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    long _begin_time = clock();
#endif
    int t, n;
    scanf("%d", &t);
    while (t--)
    {
        while (!s.empty())
            s.pop();
        l.clear();
        r.clear();
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &h[i]);
            while (!s.empty() && h[s.top()] <= h[i])
                s.pop();
            s.push(i);
        }
        for (int i = 1; i <= n; i++)    //顺时针
        {
            while (!s.empty() && h[s.top()] <= h[i])
                s.pop();
            if (!s.empty())
                l.push_back(s.top());
            else
                l.push_back(-1);
            s.push(i);
        }
        while (!s.empty())
            s.pop();
        for (int i = n; i > 0; i--)
        {
            while (!s.empty() && h[s.top()] <= h[i])
                s.pop();
            s.push(i);
        }
        for (int i = n; i > 0; i--)
        {
            while (!s.empty() && h[s.top()] <= h[i])
                s.pop();
            if (!s.empty())
                r.push_front(s.top());
            else
                r.push_front(-1);
            s.push(i);
        }
        int sz = l.size();
        for (int i = 0; i < sz; i++)
            printf("%d %d\n", l[i], r[i]);
    }
#ifndef ONLINE_JUDGE
    long _end_time = clock();
    printf("time = %ld ms.", _end_time - _begin_time);
#endif
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值