单调栈POJ2796


Bill is developing a new mathematical theory for human emotions. His recent investigations are dedicated to studying how good or bad days influent people's memories about some period of life. 

A new idea Bill has recently developed assigns a non-negative integer value to each day of human life. 

Bill calls this value the emotional value of the day. The greater the emotional value is, the better the daywas. Bill suggests that the value of some period of human life is proportional to the sum of the emotional values of the days in the given period, multiplied by the smallest emotional value of the day in it. This schema reflects that good on average period can be greatly spoiled by one very bad day. 

Now Bill is planning to investigate his own life and find the period of his life that had the greatest value. Help him to do so.
Input
The first line of the input contains n - the number of days of Bill's life he is planning to investigate(1 <= n <= 100 000). The rest of the file contains n integer numbers a1, a2, ... an ranging from 0 to 10  6 - the emotional values of the days. Numbers are separated by spaces and/or line breaks.
Output
Print the greatest value of some period of Bill's life in the first line. And on the second line print two numbers l and r such that the period from l-th to r-th day of Bill's life(inclusive) has the greatest possible value. If there are multiple periods with the greatest possible value,then print any one of them.
Sample Input
6
3 1 6 4 5 2
Sample Output
60
3 5

题意:找出一段区间使sum(l,r) * min(h[l~r]) 最大。

题解:单调栈裸题。

 
 
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <stdlib.h>

using namespace std;
typedef long long ll;
struct node
{
    int pos, val, pre, nxt;
    node() {}
    node(int a=0,int b=0,int c=0,int d=0):pos(a),val(b),pre(c),nxt(d){}
};

int h[100007];
ll sum[100007];
int main()
{
    stack<node> sta;
    int n;
    scanf("%d", &n);
    for(int i = 1;i <= n;i ++) scanf("%d", &h[i]), sum[i]=h[i]+sum[i-1];
    h[n+1] = 0;
    ll res = 0;
    int l = 1, r = 1;
    for(int i = 1;i <= n + 1;i ++) {
        node now(i, h[i], 1, 1);
        while(!sta.empty() && now.val <= sta.top().val) {
            node top = sta.top(); sta.pop();
            if(!sta.empty()) sta.top().nxt += top.nxt;
            now.pre += top.pre;
            ll tmp = top.val * (sum[top.pos+top.nxt-1] - sum[top.pos-top.pre]);
            if(tmp > res) {
                res = tmp;
                l = top.pos - top.pre + 1;
                r = top.pos + top.nxt - 1;
            }
        }
        sta.push(now);
    }
    printf("%lld\n%d %d\n", res, l, r);
    return 0;
}
/**
题意:找出一段区间使sum(l,r) * min(h[l~r]) 最大。

题解:单调栈裸题。

**/



猜你喜欢

转载自blog.csdn.net/qq_36876305/article/details/80217577
今日推荐