3401: [Usaco2009 Mar]Look Up 仰望
Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 360 Solved: 217
[Submit][Status][Discuss]
Description
约翰的N(1≤N≤105)头奶牛站成一排,奶牛i的身高是Hi(l≤Hi≤1,000,000).现在,每只奶牛都在向左看齐.对于奶牛i,如果奶牛j满足i<j且Hi<Hj,我们可以说奶牛i可以仰望奶牛j. 求出每只奶牛离她最近的仰望对象.
Input
第1行输入N,之后每行输入一个身高.
Output
共N行,按顺序每行输出一只奶牛的最近仰望对象.如果没有仰望对象,输出0.
Sample Input
6
3
2
6
1
1
2
3
2
6
1
1
2
Sample Output
3
3
0
6
6
0
3
0
6
6
0
HINT
N <= 10^5
裸的不能再裸的单调栈
维护递增站,弹栈的时候标记一下,最后剩的都孤独终老就OK
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
using namespace std;
const int N=100009;
int n,top=0;
struct data
{
int num,rank;
};
data a[N],s[N];
int love[N];//the cow love~~~
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}
return f*x;
}
int main()
{
n=read();
for(int i=1;i<=n;i++)
a[i].num=read(),a[i].rank=i;
for(int i=1;i<=n;i++)
{
while(a[i].num>s[top].num&&top>0)
{
love[s[top].rank]=a[i].rank;
top--;
}
s[++top]=a[i];
}
while(top)
{
love[s[top].rank]=0;
top--;
}
for(int i=1;i<=n;i++)
printf("%d\n",love[i]);
}