SCU 2511 Moooo(单调栈模板题)

来源:互联网 发布:风云卫星遥感数据网 编辑:程序博客网 时间:2024/06/05 15:13

题意:给出n头牛,每头牛都会发出一个噪声,为v[i]。这个噪声只会被与他相邻高度严格比他高的牛所听到,问牛收到的最大的噪音是多少。

解法:因为我是在黄学长博客上找的题目23333,所以就是一道单调栈的模板题了。BZOJ又把这题藏起来了,还好SCU上面有这道题。

直接正着跑一遍,如果当前牛的高度低于栈顶牛的高度,则入栈,否则,让栈里面高度比他低的牛都出栈,并且对应的噪声加到当前牛上面,然后再把这头牛入栈。

然后反着跑一遍。

然后找一找最大值是多少即可。

代码如下:

#include<cstdio>#include<utility>#include<stack>#include<cstring>using namespace std;typedef pair<int, int> pii;const int maxn = 5e4 + 5;int h[maxn], v[maxn];int sum[maxn];stack <pii> sta;int n;int main() {#ifndef ONLINE_JUDGEfreopen("in.txt", "r", stdin);//    freopen("out.txt", "w", stdout);#endifwhile(scanf("%d", &n) != EOF) {while(!sta.empty())sta.pop();memset(sum, 0, sizeof(sum));for(int i = 0; i < n; i++) {scanf("%d%d", &h[i], &v[i]);}sta.push(pii(h[0], v[0]));for(int i = 1; i < n; i++) {while(!sta.empty() && sta.top().first < h[i]) {sum[i] += sta.top().second;sta.pop();}sta.push(pii(h[i], v[i]));}while(!sta.empty())sta.pop();sta.push(pii(h[n - 1], v[n - 1]));for(int i = n - 2; i >= 0; i--) {while(!sta.empty() && sta.top().first < h[i]) {sum[i] += sta.top().second;sta.pop();}sta.push(pii(h[i], v[i]));}int Max = 0;for(int i = 0; i < n; i++) {if(Max < sum[i])Max = sum[i];}printf("%d\n", Max);}return 0;}


原创粉丝点击