码迷,mamicode.com
首页 > 其他好文 > 详细

NOJ1175---Dress, Left Dress!(单调栈)

时间:2015-05-07 22:18:31      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:单调栈

Maybe you think this problem is about girls and ladies.
But you’re wrong. ‘Left dress’ means ‘Eyes left’. It’s used in armed forces. It will make a square more orderly.
Now several soldiers stand in a line. They are in diffient height or the same. When each of them eyes left, the first man he will see is the nearest man higher than him.
For each soldier, you should tell me the height of the first man he will see when his eyes left.
输入
This problem has several cases.
The first line of each case is an integer N (1 < N <= 1 000 000).
Then follows a line with N integers. Indicates the height of each man. (1 <= height <= 1 000 000).
输出
For each case, you should output everyone’s first man’s position. If one has no first man, then output -1.
样例输入

5
1 3 2 5 8
4
5 4 3 2

样例输出

-1 -1 1 -1 -1
-1 0 1 2

提示

来源

XadillaX

操作

记得很久以前写过这题,方法是yy出来的
原来的方法

最近单调栈频繁出现,所以打算学习下

/*************************************************************************
    > File Name: NOJ1175.cpp
    > Author: ALex
    > Mail: zchao1995@gmail.com 
    > Created Time: 2015年05月07日 星期四 18时03分26秒
 ************************************************************************/

#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>

using namespace std;

const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;

static const int N = 1000100;
stack <PLL> st;
int arr[N];
int ans[N];

int main() {
    int n;
    while (~scanf("%d", &n)) {
        for (int i = 0; i < n; ++i) {
            ans[i] = -1;
            scanf("%d", &arr[i]);
        }
        while (!st.empty()) {
            st.pop();
        }
        for (int i = n - 1; i >= 0; --i) {
            if (st.empty()) {
                st.push(make_pair(arr[i], i));
            }
            else {
                while (!st.empty()) {
                    PLL u = st.top();
                    if (u.first >= arr[i]) {
                        break;
                    }
                    st.pop();
                    ans[u.second] = i;
                }
                st.push(make_pair(arr[i], i));
            }
        }
        printf("%d", ans[0]);
        for (int i = 1; i < n; ++i) {
            printf(" %d", ans[i]);
        }
        printf("\n");
    }
    return 0;
}

NOJ1175---Dress, Left Dress!(单调栈)

标签:单调栈

原文地址:http://blog.csdn.net/guard_mine/article/details/45564723

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!