洛谷P2947 [USACO09MAR]向右看齊Look Up

鏈接:P2947

題目描述
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;


單調棧的思想
則如果棧爲空或入棧元素值小於棧頂元素值,則入棧;否則,如果入棧則會破壞棧的單調性,則需要把比入棧元素小的元素全部出棧。單調遞減的棧反之。
具體單調棧的博客
大佬%%%
代碼:

#include <cstdio>
#include <iostream>
using namespace std;
int n,h[100001],b[100001],stack[100001],top=1;
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    scanf("%d",&h[i]);
    stack[1]=1;
    for (int i=2;i<=n;i++)
    {
        while (h[i]>h[stack[top]] && top>=1)  //這裏單調棧存儲的是下標值
        {
            b[stack[top]]=i;
            top--;
        }
        top++;
        stack[top]=i;
    }
    while (top>=1)
    b[stack[top--]]=0;  //最後沒有出棧的數據說明沒有看到的
    for (int i=1;i<=n;i++)
    printf("%d\n",b[i]);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章