洛谷p1901发射站GuanYiQiao2024-11-022024-11-02AC代码: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354//单调栈类问题#include <bits/stdc++.h>using namespace std;int n;int h[1000000],v[1000000];int le[1000000],ri[1000000];int ans=-100;//存储接收到的能量最大的发射站所接受的能量int ma[1000000]={0};stack<int>st;//模拟单调栈的栈int main(){ cin>>n; for(int i=1;i<=n;i++) { cin>>h[i]>>v[i]; } //先从右到左遍历,构建right 存储第i个点发射站右边的第一个比它高的发射站 若没有 则right[i]=0 for(int i=n;i>=1;i--) { while(!st.empty()&&h[st.top()]<=h[i]) { st.pop(); } ri[i]=st.empty()?0:st.top(); st.push(i); } //清空栈 while(!st.empty()) { st.pop(); } //从左到右遍历 填充数组le for(int i=1;i<=n;i++) { while(!st.empty()&&h[st.top()]<=h[i]) { st.pop(); } le[i]=st.empty()?0:st.top(); st.push(i); } //找接收到能量值最大的发射站 for(int i=1;i<=n;i++) { ma[ri[i]]+=v[i]; ma[le[i]]+=v[i]; } for(int i=1;i<=n;i++) { ans=max(ans,ma[i]); } cout<<ans<<endl; return 0;} 和p5788一样 这个是双向遍历进行单调栈 [视频内嵌代码]