poj 2796 分类: poj 2015-08-10 15:38 8人阅读 评论(0) 收藏


如果确定了 ax 为最小值,那么包含 ax 并且以 ax 为最小值的区间个数是 O(N2) 的。

因为序列中所有数的值非负,所以只需要考虑满足以上条件的最长区间即可。

而包含 ax 并且以 ax 为最小值的最长区间可以用两次单调队列求出,最后对每个 ax 计算答案即可。


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}

#define REP(__i,__st,__ed) for(int __i = (__st); __i <= (__ed); __i++)
#define _REP(__i,__st,__ed) for(int __i = (__st); __i >= (__ed); __i--)
const int maxn = 1e5 + 50;

int n, a[maxn], pre[maxn], sur[maxn];
int stack[maxn], top;
long long ans, sum[maxn];
int ansl, ansr;

void init()
{
    read(n);
    REP(i, 1, n) read(a[i]);
}
void prework()
{
    REP(i, 1, n) sum[i] = sum[i - 1] + a[i];

    REP(i, 1, n)
    {
        while(top && a[i] <= a[stack[top]]) stack[top--] = 0;
        pre[i] = (top?stack[top]:0) + 1, stack[++top] = i;
    }

    top = 0;

    _REP(i, n, 1)
    {
        while(top && a[i] <= a[stack[top]]) stack[top--] = 0;
        sur[i] = (top?stack[top]:(n + 1)) - 1, stack[++top] = i;
    }
}
void solve()
{
    ans = a[1], ansl = ansr = 1;

    REP(i, 1, n)
    {
        long long calc = (sum[sur[i]] - sum[pre[i] - 1])*a[i];
        if(calc > ans) ans = calc, ansl = pre[i], ansr = sur[i];
    }

    write(ans), puts("");
    write(ansl), putchar(' '), write(ansr);
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("2796.in","r",stdin);
    freopen("2796.out","w",stdout);
#endif

    init();

    prework();

    solve();


#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;           
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-10 15:38  <Dash>  阅读(139)  评论(0编辑  收藏  举报