SPOJ

来源:互联网 发布:pc安装mac os x10.9 编辑:程序博客网 时间:2024/06/01 09:04

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;}
原创粉丝点击