NCSTOJ 1554 仰视奶牛

版权声明:本文为博主原创文章,记录蒟蒻的成长之路,欢迎吐槽~ https://blog.csdn.net/PegasiTIO/article/details/89341994

Description

约翰有N头奶牛,编号为1到N。现在这N头奶牛按编号从小到大的顺序站成了一排,其中奶牛 i 的身高为Hi。现在,每头奶牛都向它的右侧望向那些编号较大的奶牛,对于奶牛 i 如果存在一头奶牛 j 满足 i < j 并且 Hi < Hj,那么我们称奶牛 i 需要仰视奶牛 j。请你求出每头奶牛的最近仰视对象。

Input

第一行包含整数N。接下来N行,每行包含一个整数Hi,其中第 i 行的数为编号为 i 的奶牛的高度。数据范围1 ≤ N ≤ 10^51 ≤ Hi ≤ 10^6

Huge input,scanf is recommened by:PegasiTio(我加的->->学学poj的感觉)

Output

共 N 行,每行输出一个整数,其中第 i 行的输出整数表示编号为 i 的奶牛的最近仰视对象的编号,如果不存在仰视对象,则输出0。

Sample Input

6 
3 
2 
6 
1 
1 
2

Sample Output

3 
3 
0 
6 
6 
0 

题目传送门

单调栈

思路和LeetCode 496.下一个更大元素I一样,比那个还简单一点,并且这道题求的是下标

cin,cout在这是真的慢,优化都不行

#include <stack>
#include <cstdio>
#include <iostream>
using namespace std;
/* static const auto io_sync_off = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}(); */

using paii = pair<int, int>;
const int maxn = 1e5 + 5;
int nums[maxn], up[maxn];

int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i)
        // cin >> nums[i];
        scanf("%d", &nums[i]);

    stack<paii> s;//第一维元素值,第二维下标
    for (int i = 1; i <= n; ++i)
    {
        while (!s.empty() && nums[i] > s.top().first)
        {
            up[s.top().second] = i;
            s.pop();
        }
        s.push(make_pair(nums[i], i));
    }

    for (int i = 1; i <= n; ++i)
        // cout << up[i] << endl;
        printf("%d\n", up[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/89341994