2019南昌icpc网络赛 I. Max answer (单调栈)

Alice has a magic array. She suggests that the value of a interval is equal to the sum of the values in the interval, multiplied by the smallest value in the interval.

Now she is planning to find the max value of the intervals in her array. Can you help her?

Input
First line contains an integer n(1 \le n \le 5 \times 10 ^5n(1≤n≤5×10
5
).

Second line contains nn integers represent the array a (-10^5 \le a_i \le 10^5)a(−10
5
≤a
i

≤10
5
).

Output
One line contains an integer represent the answer of the array.

样例输入 复制
5
1 2 3 4 5
样例输出 复制
36

题意:给以一段整数序列,寻找某一子序列,使得(子序列中的最小值乘以子序列所有元素和)的值最大,这个题和poj 2796很像,但是要注意这个题序列值有可能为负数

分析:对于每一个数,假设他是最小值,求出它的最优区间(用单调栈预先将每一个数左右第一个比他小的数的位置算出),正数负数分别考虑。

#include 
#define INF 0x3f3f3f3f
#define d(x) cout << (x) << endl
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod = 1e9 + 7;
const int N = 5e5 + 10;

int n, x, y;
ll maxn = -INF;
int a[N];	
int b[N];	//用单调栈时会改变数组的值,用b数组存一下
int tmp[N];
ll sum[N];
P pre[N];	//保存每个数左右第一个比他小的数的下标
stack<int> s;

void init()     //先算出每个值向左向右第一个比他小的数出现的位置
{
    a[n + 1] = -INF;
    for (int i = 1; i <= n+1; i++){
        if(s.empty() || a[i] >= a[s.top()]){
            s.push(i);
            tmp[i] = i;
        }else{
            int top;
            ll ans;
            while(!s.empty() && a[i] < a[s.top()]){
                top = s.top();
                s.pop();
                pre[tmp[top]] = make_pair(top-1, i - 1);
            }
            s.push(top);
            tmp[top] = i;
            a[top] = a[i];
        }
    }
    // for(int i = 1; i <= n; i++){
    //     printf("%d %d\n", pre[i].first, pre[i].second);
    // }
}

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
        b[i] = a[i];
        sum[i] = sum[i - 1] + a[i];     //前缀和数组
    }
    init();
    for(int i = 1; i <= n; i++){
        if(b[i] > 0){
            ll ans = (sum[pre[i].second] - sum[pre[i].first]) * b[i];
            maxn = max(maxn, ans);
            // d(maxn);
        }else if(b[i] < 0){
            ll ansl = 0;
            ll ansr = 0;
            ll ansll = 0;
            ll ansrr = 0;
            for (int j = i - 1; j >= 1; j--){
                if(j < 0)
                    break;
                if(b[j] < b[i]){
                    break;
                }else{
                    ansl += b[j];
                    ansll = min(ansll, ansl);
                }
            }
            for (int j = i + 1; j <= n; j++){
                if(j == n)
                    break;
                if(b[j] < b[i]){
                    break;
                }else{
                    ansr += b[j];
                    ansrr = min(ansrr, ansr);
                }
            }
            maxn = max(maxn, (ansll + ansrr + b[i]) * b[i]);
            // d(maxn);
        }else{
            maxn = max(maxn, ll(0));
        }
    }
    printf("%lld\n", maxn);
    return 0;
}

你可能感兴趣的:(解题报告,比赛,单调栈)