【POJ 2796】 Feel Good(单调栈)

Feel Good
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 12134 Accepted: 3376
Case Time Limit: 1000MS Special 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 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

**【题解】【第一次写单调栈……其实和单调队列还是蛮像的】
【这个题,是要求一个递增区间,输出的是这个区间的和乘这个区间里的最小值,要求这个最小值最大,并输出这个区间的左右端点】
【首先,在读入的时候,要初始化前缀和还有包含当前点的区间的左右端点,最开始的时候,左右端点是当前点。然后运用单调栈来处理 】
【维护一个递增的栈,每次向里面插元素的时候,先将所有大于当前点的值全部出栈,在出栈前要伸展区间的左右端点(因为维护的是递增的序列,所以出栈的数其实都可以包含在当前区间)。 再将所有元素都处理完后,将所有元素都出栈,并同时再度伸展每个区间的左右端点,以防有没有更新到位的】
【在输出时,用前缀和来寻找递增区间和乘区间最小值的最大值】**

#include
#include
#include
#define ll long long
using namespace std;
struct zhan{
    ll l,r;
}a[100010];
ll n,tot,stack[100010],d[100010],sum[100010],maxn,ansl,ansr;
inline void init(ll x)
{
    if (x==1) {stack[++tot]=x; return;}
    while(d[stack[tot]]>=d[x]&&tot)
     {
       a[x].l=a[stack[tot]].l;
       a[stack[tot-1]].r=a[stack[tot]].r;
       tot--;   
     }
    a[stack[tot]].r=a[x].r;
    stack[++tot]=x;
    return;
}
inline void pop()
{
    a[stack[tot-1]].r=a[stack[tot]].r;
    tot--;
}
int main()
{
  ll i,j;
  scanf("%lld",&n);
  for (i=1;i<=n;i++)
   {
    scanf("%lld",&d[i]);
    sum[i]=sum[i-1]+d[i];
    a[i].l=a[i].r=i;
   }
  for(i=1;i<=n;++i) init(i);
  while(tot) pop();
  for(i=1;i<=n;++i)
   {
    ll s1=sum[a[i].r]-sum[a[i].l-1];
    if (maxn<=s1*d[i]) maxn=s1*d[i],ansl=a[i].l,ansr=a[i].r;
   }
  printf("%lld\n",maxn);
  printf("%lld %lld\n",ansl,ansr);
  return 0;
}

你可能感兴趣的:(模板,POJ,单调栈,线性)