LuoGu_2947 [USACO09MAR] 向右看齐 Look Up

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SSLGZ_CJX/article/details/81744909

题目描述

约翰的N(1≤N≤10^5)头奶牛站成一排,奶牛i的身高是Hi(l≤Hi≤1,000,000).现在,每只奶牛都在向右看齐.对于奶牛i,如果奶牛j满足i<j且Hi<Hj,我们可以说奶牛i可以仰望奶牛j. 求出每只奶牛离她最近的仰望对象.

输入输出格式

输入格式:

* Line 1: A single integer: N

* Lines 2..N+1: Line i+1 contains the single integer: H_i

第 1 行输入 N,之后每行输入一个身高 H_i。

输出格式:

* 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 行,按顺序每行输出一只奶牛的最近仰望对象,如果没有仰望对象,输出 0。

输入输出样例

输入样例#1: 

6 
3 
2 
6 
1 
1 
2 

输出样例#1: 

3 
3 
0 
6 
6 
0 

思路:

建立一个单调上升的序列,每当有一个元素大于栈顶元素,则不断出栈直到满足单调上升后在入栈,并将出栈元素的仰慕对象标为新入栈的元素,最后输出即可。

原理可以自己模拟一遍便可知

// luogu-judger-enable-o2
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>

using namespace std;

int a[100005][3],n,m,t,z[3][100005],mark[100005];

int main()
{
    scanf("%d",&n);
    z[1][0]=23333333;
    int l=1,r=0;
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&a[i][1]);
        if (a[i][1]<z[1][r])r++,z[1][r]=a[i][1],z[2][r]=i;
         else
         { 
             while (a[i][1]>z[1][r])
             {
             	a[z[2][r]][2]=i;
             	z[2][r]=z[1][r]=0;
                r--;
             }		
             r++;
             z[1][r]=a[i][1];
             z[2][r]=i;
         }
    }
    for (int i=1;i<=n;i++)
    printf("%d\n",a[i][2]);
}

猜你喜欢

转载自blog.csdn.net/SSLGZ_CJX/article/details/81744909