UVa 1619:Feel Good(单调栈)

题目链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值