仰视奶牛

仰视奶牛

单调栈

对于当前的每个奶牛,找到右边离他最近的,且比他大的奶牛

原问题转化为对于每个奶牛,找到左边离他最近的,且比他小的奶牛

注意下标的存储

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef pair<int,int> PII;
#define endl '\n'
stack<PII> stk;
int a[N],s[N],n;
int main() {
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n; ++i) cin >> a[i];
    for(int i = 1;i <= n; ++i) {
        while(stk.size() && a[i] > stk.top().first) {
            s[stk.top().second] = i;
            stk.pop();
        }
        stk.push({a[i],i});
    }
    for(int i = 1;i <= n; ++i) cout << s[i] <<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lukelmouse/p/12367324.html