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

75 篇文章 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值