[TIOJ]1721. 山上的風景

題目連結:http://tioj.ck.tp.edu.tw/problems/1721

用stack維護嚴格遞減。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <queue>
#include <vector>
#include <stack>
#define lld long long
#define PB push_back
#define F first
#define S second
#define jizz cin.tie(0);ios_base::sync_with_stdio(0);
#define endl '\n'
using namespace std;
typedef pair<int,int> Pair;
int a[100005],ans[100005];
int main(){jizz
    int n;
    while(cin >> n){
        stack<Pair> s;
        fill(ans,ans+100005,0);
        for(int i = 1 ; i <= n ;i++)cin >> a[i];
        for(int i = 1 ; i <= n ; i++){
            while(!s.empty() && s.top().F < a[i])s.pop();
            if(!s.empty())ans[i] += (i-s.top().S);
            else ans[i] += i-1;
            s.push({a[i],i});
        }
        while(!s.empty())s.pop();
        for(int i = n ; i >= 1; i--){
            while(!s.empty() && s.top().F < a[i])s.pop();
            if(!s.empty())ans[i] += (s.top().S-i);
            else ans[i] += (n-i);
            s.push({a[i],i});
        }
        for(int i = 1 ; i <= n; i++)cout << ans[i]+1 << ' ' ;
        cout << endl;
    }
    return 0;
}


留言

這個網誌中的熱門文章

[TIOJ]1617. [Interactive] 中位數

[TIOJ]1337. 隕石

[TIOJ]1994. 冰塊線