2019南昌ICPC网络赛 I Max answer【单调栈+ST表】

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×105).

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

Output

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

样例输入复制

5
1 2 3 4 5

样例输出复制

36

看到这道题的时候我是乐坏了的,这不是单调栈吗

交了几发WA之后是自闭的,然后发现这题的数据可以是负数

然后就不会处理了、、

补题,需要用到ST表来查找区间内的最值,??

刚学的ST表,涨姿势了

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf = 1e17;
const int maxn = 500000 + 10;
int a[maxn];
int st[maxn];
int posl[maxn],posr[maxn];
ll sum[maxn];
ll mx[maxn][32],mi[maxn][32];
ll ans;
int n;
void ST_prework(){
  for(int i = 0; i <= n; i++)  
    mx[i][0] = mi[i][0] = sum[i];
  int  t = log(n) / log(2) + 1;
  for(int j = 1; j < t; j++)
    for(int i = 0; i <= n - (1 << j) + 1; i++){
      mx[i][j] = max(mx[i][j - 1],mx[i + (1 << (j-1))][j - 1]);
      mi[i][j] = min(mi[i][j - 1],mi[i + (1 << (j-1))][j - 1]);
    }
}
ll ST_querymax(int l,int r){
  int k = log(r - l + 1)/log(2);
  return max(mx[l][k],mx[r - (1 << k) + 1][k]);
}
ll ST_querymin(int l,int r){
  int k = log(r - l + 1)/log(2);
  return min(mi[l][k],mi[r - (1 << k) + 1][k]);
}
int main()
{
    scanf("%d",&n);
    for (int i = 1; i <= n; i++){
        scanf("%d",&a[i]);
        sum[i] = sum[i - 1] + a[i];
    }
    ST_prework();

    int top = 0;
    for(int i = 1; i <= n; i++){
      if(top == 0 || a[i] > a[st[top - 1]]){
        st[top++] = i;
        posl[i] = i;
      }
      else{
         while (top >= 1 && a[i] <= a[st[top - 1]]){
           --top;
         }
         posl[i] = posl[st[top]];
         st[top++] = i;
      }
    }
    memset(st,0,sizeof st);
    top = 0;
    for(int i = n; i >= 1; i--){
      if(top == 0 || a[i] > a[st[top - 1]]){
        st[top++] = i;
        posr[i] = i;
      }
      else{
         while (top >= 1 && a[i] <= a[st[top - 1]]){
           --top;
         }
         posr[i] = posr[st[top]];
         st[top++] = i;
      }
    }
    ans = -inf;
    for(int i = 1; i <= n; i++){
      if(a[i] > 0){
        ll l = ST_querymin(posl[i] - 1,i -1);
        ll r = ST_querymax(i,posr[i]);
        ll tmp = (r - l) * a[i];
        ans = max(ans,tmp);
      }
      else {
        ll l = ST_querymax(posl[i] - 1,i - 1);
        ll r = ST_querymin(i,posr[i]);
        ll tmp = (r - l) * a[i];
        ans = max(ans,tmp);
      }
    }
    printf("%lld\n", ans);
    return 0;
}
发布了89 篇原创文章 · 获赞 6 · 访问量 7915

猜你喜欢

转载自blog.csdn.net/kl782636177/article/details/89437564
今日推荐