[USACO09MAR]Look Up S
题目描述
Farmer John’s N (1 <= N <= 100,000) cows, conveniently numbered 1…N, are once again standing in a row. Cow i has height H_i (1 <= H_i <= 1,000,000).
Each cow is looking to her left toward those with higher index numbers. We say that cow i ‘looks up’ to cow j if i < j and H_i < H_j. For each cow i, FJ would like to know the index of the first cow in line looked up to by cow i.
Note: about 50% of the test data will have N <= 1,000.
约翰的 N ( 1 ≤ N ≤ 1 0 5 ) N(1\le N\le10^5) N(1≤N≤105) 头奶牛站成一排,奶牛 i i i 的身高是 H i ( 1 ≤ H i ≤ 1 0 6 ) H_i(1\le H_i\le10^6) Hi(1≤Hi≤106)。现在,每只奶牛都在向右看齐。对于奶牛 i i i,如果奶牛 j j j 满足 i < j i<j i<j 且 H i < H j H_i<H_j Hi<Hj,我们可以说奶牛 i i i 可以仰望奶牛 j j j。 求出每只奶牛离她最近的仰望对象。
Input
输入格式
- * Line 1: A single integer: N
* Lines 2…N+1: Line i+1 contains the single integer: H_i
第 1 1 1 行输入 N N N,之后每行输入一个身高 H i H_i Hi。
输出格式
* Lines 1…N: Line i contains a single integer representing the smallest index of a cow up to which cow i looks. If no such cow exists, print 0.
共 N N N 行,按顺序每行输出一只奶牛的最近仰望对象,如果没有仰望对象,输出 0 0 0。
样例 #1
样例输入 #1
6
3
2
6
1
1
2
样例输出 #1
3
3
0
6
6
0
提示
FJ has six cows of heights 3, 2, 6, 1, 1, and 2.
Cows 1 and 2 both look up to cow 3; cows 4 and 5 both look up to cow 6; and cows 3 and 6 do not look up to any cow.
【输入说明】 6 6 6 头奶牛的身高分别为 3,2,6,1,1,2。
【输出说明】奶牛 #1,#2 仰望奶牛 #3,奶牛 #4,#5 仰望奶牛 #6,奶牛 #3 和 #6 没有仰望对象。
【数据规模】
对于 20 % 20\% 20% 的数据: 1 ≤ N ≤ 10 1\le N\le10 1≤N≤10;
对于 50 % 50\% 50% 的数据: 1 ≤ N ≤ 1 0 3 1\le N\le10^3 1≤N≤103;
对于 100 % 100\% 100% 的数据: 1 ≤ N ≤ 1 0 5 , 1 ≤ H i ≤ 1 0 6 1\le N\le10^5,1\le H_i\le10^6 1≤N≤105,1≤Hi≤106。
答案
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream>
#include<deque>
using namespace std;
typedef long long LL;
const int inf=0x3f3f3f3f;
const int N=1e6+10;
int n;
int a[N];
int ans[N];
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
// for(int i=0;i<n;i++)
// {
// int flag=1;
// for(int j=i+1;j<n;j++)
// {
// if(a[j]>a[i]) {flag=0;cout<<j+1<<endl;break;}
// }
// if(flag==1)
// cout<<0<<endl;
//
// }
stack<int> st;
for(int i=n-1;i>=0;i--)
{
while(!st.empty()&&a[st.top()]<=a[i]) st.pop();//当栈顶奶牛没有i高,则栈顶出栈,保证栈顶最大
if(st.empty()) ans[i]=0;//栈空,没有仰望对象
else ans[i]=st.top()+1;//
st.push(i);
}
for(int i=0;i<n;i++)
{
cout<<ans[i]<<endl;
}
return 0;
}