UVa 1619:Feel Good(单调栈)

来源:互联网 发布:氨基酸洗面奶知乎 编辑:程序博客网 时间:2024/06/10 00:37

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=4494

题意:给出一个长度为n(n100000)的正整数序列ai,求出一段连续子序列al,...,ar,使得(al+...+ar)min{al,...,ar}尽量大。(本段摘自《算法竞赛入门经典(第2版)》)

分析:枚举每一个数,利用单调栈计算以它为最小值向左向右最远能够延伸到多远,每次更新答案即可。(注意:UVa这题貌似比较坑,题目中说如果有多组解,输出任意组即可,但是貌似不是的。具体输出看代码。)

代码:

#include <iostream>#include <fstream>#include <cstring>#include <vector>#include <queue>#include <cmath>#include <stack>using namespace std;const int maxn = 1000000 + 5;int n, L, R;int l[maxn], r[maxn];bool first;long long ans, tmp;long long a[maxn], sum[maxn];int main(){    while (~scanf("%d", &n))    {        if (first)            printf("\n");        else            first = true;        for (int i = 1; i <= n; ++i)        {            scanf("%lld", &a[i]);            sum[i] = sum[i - 1] + a[i];        }        a[0] = -1;        l[0] = 0;        stack< int > sta1;        sta1.push(0);        for (int i = 1; i <= n; ++i)        {            while (a[sta1.top()] >= a[i])                sta1.pop();            l[i] = sta1.top() + 1;            sta1.push(i);        }        a[n + 1] = -1;        r[n + 1] = n + 1;        stack< int > sta2;        sta2.push(n + 1);        for (int i = n; i >= 1; --i)        {            while (a[sta2.top()] >= a[i])                sta2.pop();            r[i] = sta2.top() - 1;            sta2.push(i);        }        L = 1;        R = 1;        ans = 0;        for (int i = 1; i <= n; ++i)        {            tmp = (sum[r[i]] - sum[l[i] - 1]) * a[i];            if (tmp > ans || (tmp == ans && R - L > r[i] - l[i]))            {                L = l[i];                R = r[i];                ans = tmp;            }        }        printf("%lld\n%d %d\n", ans, L, R);    }    return 0;}
0 0