传送门
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 106 - 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
Source
Northeastern Europe 2005
题目大意
n个数,求某段区间的最小值*该段区间所有元素之和的最大值
解题思路
主要思想
递增单调栈求区间+前缀和求答案
计算方法
把以每个数为最小数的区间都求出来
m
a
x
(
a
[
i
]
∗
(
前
缀
和
[
右
端
点
]
−
前
缀
和
[
左
端
点
−
1
]
)
)
max(a[i]*(前缀和[右端点]-前缀和[左端点-1]))
max(a[i]∗(前缀和[右端点]−前缀和[左端点−1]))(1<=i<=n)
详细做法
求区间过程用两个递增单调栈做:
- 一个从左往右找,求以当前数为最小数的区间的左端点
- 一个从右往左找,求以当前数为最小数的区间的右端点
注意
- 一开始所有数的左端点和右端点都设为自己
- 每次弹出一个数时,要更新一下当前数的左端点,而且是更新成弹出数的左端点
到第4个数时弹出前三个,左端点不断更新(3,2,1)
到第5个数时弹出前一个(第4个数),左端点更新为这个弹出数的左端点(1) - 找左端点的循环是 1 1 1~ n n n,找右端点的循环是 n n n ~ 1 1 1
Code
#include<iostream>
#include<cstdio>
using namespace std;
struct DT{
long long v,l,r;
}a[100005];
long long n,ans,ansl,ansr,top,que[100005],sum[100005];
int main(){
scanf("%lld",&n);
for(int i=1;i<=n;i++){
scanf("%lld",&a[i].v);
sum[i]=sum[i-1]+a[i].v;
a[i].l=a[i].r=i;
}
for(int i=1;i<=n;i++){//寻找左端点
while(top&&a[que[top]].v>=a[i].v){
a[i].l=a[que[top]].l;//更新左端点
top--;
}
que[++top]=i;
}
top=0;
for(int i=n;i>=1;i--){//寻找右端点
while(top&&a[que[top]].v>=a[i].v){
a[i].r=a[que[top]].r;//更新右端点
top--;
}
que[++top]=i;
}
ans=-1;
for(int i=1;i<=n;i++){
if(a[i].v*(sum[a[i].r]-sum[a[i].l-1])>ans){
ans=a[i].v*(sum[a[i].r]-sum[a[i].l-1]);//更新答案
ansl=a[i].l,ansr=a[i].r;//记录区间的左端点和右端点
}
}
printf("%lld\n%lld %lld",ans,ansl,ansr);
}