3.14 周六晚上--单调栈2

· · 个人记录

3.14 周六晚上--单调栈2

P1901 发射站

我们想要知道每个发射站能接收到哪个发射站的能量,我们可以用两个单调栈来写,用来找到左右两边第一个比它高的可以接受到能量的发射站。最后将每个发射站接收到的能量总和加起来。

#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=1e6+10;
int a[N],f1[N],f2[N],n,v[N],sum[N];
stack<int>st1,st2; 
signed main(){
    cin>>n;
    for(int i=1;i<=n;++i){
        cin>>a[i]>>v[i];
    }
    for(int i=1;i<=n;++i){
        while(st1.size()&&a[i]>a[st1.top()]){
            f1[st1.top()]=i;
            st1.pop();
        }
        st1.push(i);
    }
    for(int i=n;i>=1;--i){
        while(st2.size()&&a[i]>a[st2.top()]){
            f2[st2.top()]=i;
            st2.pop();
        }
        st2.push(i);
    }
    int ans=0;
    for(int i=1;i<=n;++i){
        sum[f1[i]]+=v[i];
        sum[f2[i]]+=v[i];
    }
    for(int i=1;i<=n;++i){
        ans=max(ans,sum[i]); 
    }
    cout<<ans<<"\n";
    return 0;
}

P8082 [COCI 2011/2012 #4] KEKS

这个只需要在单调栈的过程中记下操作的次数,如果不小于 k 就停止操作。

#include<bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n,k,cnt;
string s,c;
stack<int>st;
signed main(){
    cin>>n>>k;
    cin>>s;
    s=" "+s;
    n++;
    for(int i=1;i<=n;++i){
        while(st.size()&&s[i]>s[st.top()]){
            if(cnt==k)break;
//          cout<<st.top()<<" ";
            st.pop();
            cnt++; 
        }
        st.push(i);
//      cnt=0;
    }
    while(st.size()){
        c+=s[st.top()];
        st.pop(); 
    } 
    reverse(c.begin(),c.end());
    cout<<c<<"\n";
    return 0;
}