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;
}

本文介绍了一个有趣的算法问题——左视士兵问题,并提供了一种利用单调栈求解的方法。问题中,一排不同高度的士兵从右向左看,每个士兵能看到左侧第一个比自己高的士兵。文章通过具体的代码实现展示了如何高效地解决这一问题。
4328

被折叠的 条评论
为什么被折叠?



