题目链接
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
题意:在给出的数列中找一段连续子区间,使这子区间的和乘以子区间的最小值,最大。并输出左右端点坐标。
题解:很容易想到我们需要求出以a[i](1<=i<=n)为最小值,子区间的左右端点能够扩充哪点。然后这样我们就可以用到单调栈了,用一个单调栈维护一个单调递增序列。然后从左向右遍历找右区间,从右向左遍历找左区间,其他细节看代码。
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e5+10;
const int mod=1e9+7;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
#define mid l+(r-l)/2
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI 3.14159265358979323846
int dir[4][2]= {0,-1,-1,0,0,1,1,0};
typedef long long ll;
using namespace std;
int a[maxn];
int que[maxn],l[maxn],r[maxn];
ll sum[maxn]= {0};
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
sum[0]=0;
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
l[i]=1,r[i]=n;
}
int head=0;
for(int i=1; i<=n; i++)
{
while(head&&a[que[head]]>a[i])
{
r[que[head]]=i-1;///当a[i]小于等于栈顶元素,a[i]一定是第一个比它小的数,以a[que[head]]为最小的右区间最多延伸到i-1
head--;
}
que[++head]=i;
}
head=0;
for(int i=n; i>=1; i--)
{
while(head&&a[que[head]]>a[i])
{
l[que[head]]=i+1;///与上面找右区间情况相同
head--;
}
que[++head]=i;
}
ll ans=-1;
int pos1,pos2;
for(int i=1; i<=n; i++)
{
ll temp=(ll)(sum[r[i]]-sum[l[i]-1])*a[i];
if(temp>ans)
ans=temp,pos1=l[i],pos2=r[i];
}
printf("%lld\n%d %d\n",ans,pos1,pos2);
}
return 0;
}