zoukankan      html  css  js  c++  java
  • 洛谷 P2947 [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 < j且Hi < Hj,我们可以说奶牛i可以仰望奶牛j. 求出每只奶牛离她最近的仰望对象.

    Input

    输入输出格式
    输入格式:
    * 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
    说明
    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 头奶牛的身高分别为 3, 2, 6, 1, 1, 2.

    【输出说明】奶牛#1,#2 仰望奶牛#3,奶牛#4,#5 仰望奶牛#6,奶牛#3 和#6 没有仰望对象。

    【数据规模】

    对于 20%的数据: 1≤N≤10;
    对于 50%的数据: 1≤N≤1,000;
    对于 100%的数据:1≤N≤100,000;1≤H_i≤1,000,000;
    .
    .
    .
    .
    .

    分析

    单调队列模板打法,因为head为1,所以要保证tail>0,当目前扫到的数大于队列末尾的数时,这个数一定是队列末尾的数,右端第一个比它大的数,所以就把这个这个数储存入队列末尾数的an数组中,并将tail–,即把末尾数移除队列,紧接着比较队列中下个数,直到遇到第一个≥这个数或队列空为止。 总的核心思想就是维护一个不上升连续序列,在维护的同时找到答案。
    .
    .
    .
    .
    .

    程序:
    #include<iostream>
    using namespace std;
    int n,a[100005],q[100005],an[100005],tail=0;
    int main()
    {
        cin>>n;
        for (int i=1;i<=n;i++) cin>>a[i];
        for (int i=1;i<=n;i++)
        {
            while (tail&&a[i]>a[q[tail]])
            {
                an[q[tail]]=i;
                tail--;
            }
            q[++tail]=i;
        }
        for (int i=1;i<=n;i++) cout<<an[i]<<endl;
        return 0;
    }
  • 相关阅读:
    2020 企业远程研发总结 —— 回首抗疫一年
    CODING X C-Life:云端 DevOps 加速企业数智化
    CODING 联合 TKE,让应用发布更便捷
    CODING 再携手腾讯云 Serverless,让开发者跑步上云
    代码托管从业者 Git 指南
    推荐计划 | 推荐好友用 CODING,获高额返现奖励
    仰望天空,脚踏实地 —— CODING OKR 全新上线
    在.NET中体验GraphQL
    C#规则引擎RulesEngine
    武装你的WEBAPI-OData常见问题
  • 原文地址:https://www.cnblogs.com/YYC-0304/p/9499896.html
Copyright © 2011-2022 走看看