链接地址:http://ac.nbutoj.com/Problem/view.xhtml?id=1175
一些士兵站在一直线上,当每一个人都向左看时,看到的第一个比自己高的那个人就是the first man。并输出the first man的位置,若不存在the first man,输出-1。将所有身高存在一数组里,然后遍历一遍,但是这样会超时!所以,必须要优化算法。 第一种方法:用栈。
我用的是另一种方法,取两个数组 height [ ] , position [ ] 。height存放身高,position存放
以下是我AC的代码:
一些士兵站在一直线上,当每一个人都向左看时,看到的第一个比自己高的那个人就是the first man。并输出the first man的位置,若不存在the first man,输出-1。将所有身高存在一数组里,然后遍历一遍,但是这样会超时!所以,必须要优化算法。
这些身高中,如果一人的身高比左边的某个人和右边的某个人都低或存在相等(这里的左边和右边不是指相邻的),那么这个人的身高是不需要在后面出现的,也就是要剔除这个人的身高。
我用的是另一种方法,取两个数组 height [ ] , position [ ] 。height存放身高,position存放
以下是我AC的代码:
#include <iostream>
#include <cstdio>
using namespace std;
int height[1000100];
int position[1000100];
int main()
{
int a,n,p;
while (~scanf("%d", &n))
{
p = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &a);
while (p > 0)
{
if (height[p-1] <= a) p--;
else break;
}
if (i > 0) printf(" ");
if (p > 0) printf("%d", position[p-1]);
else printf("-1");
position[p] = i;
height[p++] = a;
}
printf("\n");
}
return 0;
}