一些士兵站在一直线上,当每一个人都向左看时,看到的第一个比自己高的那个人就是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;
}
519



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



