洛谷2947 [USACO09MAR]向右看齐Look Up 单调队列

题目

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≤10^5)头奶牛站成一排,奶牛i的身高是Hi(l≤Hi≤1,000,000).现在,每只奶牛都在向右看齐.对于奶牛i,如果奶牛j满足i

题解

大大的水,原来世界上真的有从看题目到AC只用8分钟的好事情

从后往前做,维护一个单调递减的队列,每个数加入队列时在队列中找到刚好比它大的数,该数放在队列中刚好比它大的数后面一个位置,该数对应的答案就是刚好比它大的数的序号

代码

#include <cstdio>

using namespace std;

int n,c;
int a[100005];
int s[100005][2];
int f[100005];

int main(){
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    s[++c][0]=a[n];s[c][1]=n;
    for (int i=n-1;i>=1;i--){
        while (a[i]>=s[c][0]&&c>0) c--;
        f[i]=s[c][1];
        s[++c][0]=a[i];s[c][1]=i;
    }
    for (int i=1;i<=n;i++)
        printf("%d\n",f[i]);
}

猜你喜欢

转载自blog.csdn.net/yjy_aii/article/details/81712046