洛谷 P1901 发射站(单调栈)

传送门


解题思路

就是对于每个点,找到左面和右面第一个比它大的点。

单调栈解决。

AC代码

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<stack>
 4 using namespace std;
 5 const int maxn=1000005;
 6 int n,ansl[maxn],a[maxn],ansr[maxn],ans[maxn],maxx,v[maxn];
 7 stack<int> s;
 8 int main()
 9 {
10     cin>>n;
11     for(int i=1;i<=n;i++){
12         scanf("%d%d",&a[i],&v[i]);
13         if(s.empty()){
14             s.push(i);
15         }else{
16             while(!s.empty()&&a[s.top()]<a[i]){
17                 ansr[s.top()]=i;
18                 s.pop();
19             }
20             if(!s.empty())ansl[i]=s.top();
21             s.push(i);
22         }
23     }
24     for(int i=1;i<=n;i++){
25         ans[ansl[i]]+=v[i];
26         ans[ansr[i]]+=v[i];
27     }
28     for(int i=1;i<=n;i++) maxx=max(maxx,ans[i]);
29     printf("%d\n",maxx);
30     return 0;
31 }

 

posted @ 2020-02-22 17:57  尹昱钦  阅读(203)  评论(0编辑  收藏  举报