您的位置:首页 > Web前端

UVa 1619:Feel Good(单调栈)

2015-08-26 11:37 387 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=4494

题意:给出一个长度为n(n≤100000)(n \le 100000)的正整数序列aia_i,求出一段连续子序列al,...,ara_l,...,a_r,使得(al+...+ar)∗min{al,...,ar}(a_l + ... +a_r)*min\{a_l,...,a_r\}尽量大。(本段摘自《算法竞赛入门经典(第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: