HDU_3410_单调栈

http://acm.hdu.edu.cn/showproblem.php?pid=3410

 

初探单调栈,从左往右,求l,从右往左,求r。

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;

int a[50005],l[50005],r[50005],n;
stack<int> s;

int main()
{
    int T;
    scanf("%d",&T);
    for(int z = 1;z <= T;z++)
    {
        while(!s.empty())   s.pop();
        printf("Case %d:\n",z);
        scanf("%d",&n);
        for(int i = 1;i <= n;i++)   scanf("%d",&a[i]);
        for(int i = 1;i <= n;i++)
        {
            int temp = -1;
            while(!s.empty() && a[s.top()] < a[i])
            {
                temp = s.top();
                s.pop();
            }
            l[i] = temp == -1?0:temp;
            s.push(i);
        }
        while(!s.empty())   s.pop();
        for(int i = n;i >= 1;i--)
        {
            int temp = -1;
            while(!s.empty() && a[s.top()] < a[i])
            {
                temp = s.top();
                s.pop();
            }
            r[i] = temp == -1?0:temp;
            s.push(i);
        }
        for(int i = 1;i <= n;i++)   printf("%d %d\n",l[i],r[i]);
    }
    return 0;
}

 

posted @ 2016-09-30 15:06  zzzzzzzzhu  阅读(133)  评论(0编辑  收藏  举报