单调栈

来源:互联网 发布:sqsxfree类似软件 编辑:程序博客网 时间:2024/05/16 04:53

单调栈—可用于从某点处向左向右扩展到符合条件的值问题的优化
这类题目 暴力的方法需要n2的复杂度 往往会被T 用单调栈可以将问题简化成n

  • 思想:通过维护一个单调的栈将满足条件左||右端点找出来
  • 函数:s.size( ) s.push( ) s.pop( ) s.top( )
    题目:数据结构训练一D - Feel Good &&E - Bad Hair Day
    qduojLC的课后辅导
    D - Feel Good
    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
题意是找一个子序列中最小值与这段子序列各数值之和的乘积的最大值 先循环一遍所有的数值 假设当前循环到的数值是这段子序列中最小的 然后向右向左找不小于它的第一个数 通过两个数组L[N]和R[N]储存
错了好几次 原因一是要预处理一下前n项和 否则会超时 二是要用longlong储存最后的和 三是不能在main函数中输入n后建数组 会崩溃
很多题目都可以通过预处理减小复杂度 一定要记得!!!

#include <iostream>#include <stack>#include <cstdio>#define ll long long#define m 100010int num[m],l[m],r[m];ll pre[m];using namespace std;int main(){    int n,i;    scanf("%d",&n);    for(i=0;i<n;i++)    {        scanf("%d",&num[i]);        if(i==0)        {            pre[i]=num[i];        }        else        {            pre[i]=num[i]+pre[i-1];        }    }    stack<int>s;    for(i=0;i<n;i++)    {        while(s.size()&&num[s.top()]>=num[i])//好好思考被弹出栈的是什么数        s.pop();        l[i]=s.size()==0?0:s.top()+1;        s.push(i);    }    while(s.size()!=0)//将栈清空    s.pop();    ll max=0;    int k=0;    for(i=n-1;i>=0;i--)    {        while(s.size()&&num[s.top()]>=num[i])        s.pop();        r[i]=s.size()==0?n-1:s.top()-1;        s.push(i);    }    for(i=0;i<n;i++)    {        ll t=(pre[r[i]]-pre[l[i]-1])*num[i];        if(t>=max)        {            max=t;            k=i;        }    }    printf("%lld\n%d %d\n",max,l[k]+1,r[k]+1);    return 0;}
原创粉丝点击