poj2796 Feel Good(单调栈)

xiaoxiao2021-02-28  46

Time Limit: 3000MSMemory Limit: 65536KTotal Submissions: 14383Accepted: 3978Case Time Limit: 1000MSSpecial Judge

Description

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

题目大意是给你一个长度为n的区间,找到一个子区间,这个子区间的所有元素之和乘以它的区间最小值要是最大的。最后输出结果和这个区间的范围。 例如样例中 区间【3,5】的值为(6,4,5) ,4*(6+4+5)=60.最大。 单调栈模版~

#include <stdio.h> #include <stack> using namespace std; typedef long long LL; const int N=1e5+10; LL num[N],sum[N]; int left[N],right[N]; int x; stack<int>s; void pushstack(int pos) { if(pos==1) { s.push(pos); return ; } x=s.top(); while(num[x]>num[pos]&&!s.empty()) { s.pop(); left[pos]=left[x];//出栈的都是大于num[pos]的 所以可以向左更新 if(s.empty()) break; right[s.top()]=right[x];//当前出栈的 一定大于出栈后的栈顶元素,所以可以向右更新 x=s.top(); } if(!s.empty()) right[s.top()]=right[pos];//当前要入栈的元素肯定大于当前栈顶元素 所以更新右坐标 s.push(pos); } int main() { int n; scanf("%d",&n); num[0]=0; for(int i=1;i<=n;i++) { scanf("%lld",&num[i]); sum[i]=sum[i-1]+num[i]; left[i]=right[i]=i; } for(int i=1;i<=n;i++) { pushstack(i); } while(!s.empty()) { x=s.top();s.pop(); if(!s.empty()) right[s.top()]=right[x]; } LL maxx=-1; int l,r; for(int i=1;i<=n;i++) { LL summ=sum[right[i]]-sum[left[i]-1]; if(maxx<summ*num[i]) maxx=summ*num[i],l=left[i],r=right[i]; } printf("%lld\n%d %d\n",maxx,l,r); }
转载请注明原文地址: https://www.6miu.com/read-43144.html

最新回复(0)