洛谷p1901发射站

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//单调栈类问题
#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一样 这个是双向遍历进行单调栈

[视频内嵌代码]