Description
Solution
显然的斜率优化,
如果只有一个询问的话直接做即可,
多个询问的话,考虑预处理3个数组:
f,g好做,主要是h,这个用分治来做,
处理跨过mid的i,j对的答案,
枚举i,发现h的式子中的j可以写成斜率的样子,这样就可以快速找到i对应最优的j了。
复杂度:
Code
#include <cstdio>
#include <algorithm>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fod(i,a,b) for(int i=a;i>=b;i--)
#define min(q,w) ((q)<(w)?(q):(w))
#define max(q,w) ((q)>(w)?(q):(w))
#define JS(q,i) (f[q]+sum[q]-sum[i]+(LL)(((i)-(q))*((i)-(q)+1)/2))
#define pre(j) ((LL)(j)*(j))
#define XL(j) (f[j]*2+sum[j]*2+pre(j)-(LL)(j))
#define XLg(j) (g[j+1]*2-sum[j]*2+pre(j)+3*(LL)(j))
#define iXL(i,j) (2*((i)-(j)))
using namespace std;
typedef long long LL;
const int N=300500,mo=1e9+7;
int read(int &n)
{
int w=1;n=0;char ch=' ';
for(;ch!='-'&&(ch<'0'||ch>'9');ch=getchar());
if(ch=='-')w=-1,ch=getchar();
for(;ch<='9'&&ch>='0';ch=getchar())n=n*10+ch-48;
return n=w*n;
}
int n,m;
LL f[N],g[N],h[N],h1[N];
int a[N];
int za[N];
LL sum[N];
void Doit()
{
za[za[0]=1]=0;
fo(i,1,n)
{
f[i]=-2e16;
for(;za[0]>1&&XL(za[za[0]])-XL(za[za[0]-1])<i*iXL(za[za[0]],za[za[0]-1]);za[0]--);
f[i]=max(JS(za[za[0]],i),f[i-1]);
for(;za[0]>1&&(XL(za[za[0]])-XL(za[za[0]-1]))*iXL(i,za[za[0]])<
(XL(i)-XL(za[za[0]]))*iXL(za[za[0]],za[za[0]-1]);za[0]--);
za[++za[0]]=i;
}
}
void divide(int l,int r)
{
if(l==r){h[l]=max(h[l],1-a[l]);return;}
int mid=(l+r)>>1;
za[0]=0;
fo(i,mid+1,r)
{
for(;za[0]>1&&(XLg(za[za[0]])-XLg(za[za[0]-1]))*iXL(i,za[za[0]])<
(XLg(i)-XLg(za[za[0]]))*iXL(za[za[0]],za[za[0]-1]);za[0]--);
za[++za[0]]=i;
}
LL mx=-2e16;
fo(i,l,mid)
{
for(;za[0]>1&&XLg(za[za[0]])-XLg(za[za[0]-1])<i*iXL(za[za[0]],za[za[0]-1]);za[0]--);
int q=za[za[0]];
mx=max(mx,f[i-1]+g[q+1]-sum[q]+sum[i-1]+(LL)(q-i+1)*(LL)(q-i+2)/2);
h[i]=max(h[i],mx);
}
divide(l,mid);
divide(mid+1,r);
}
int main()
{
freopen("genocide.in","r",stdin);
freopen("genocide.out","w",stdout);
int q,w;
read(n);
fo(i,1,n)read(a[n-i+1]),h[i]=h1[i]=-2e16;
fo(i,1,n)sum[i]=sum[i-1]+(LL)a[i];
Doit();
fo(i,1,n)g[n-i+1]=f[i];
fo(i,1,n/2)swap(a[i],a[n-i+1]);
fo(i,1,n+1)sum[i]=sum[i-1]+(LL)a[i];
Doit();
divide(1,n);
fo(i,1,n/2)swap(a[i],a[n-i+1]);
fo(i,1,n+1)sum[i]=sum[i-1]+(LL)a[i],swap(f[n-i+1],g[i]),swap(h[i],h1[i]);
divide(1,n);
fo(i,1,n/2)swap(h[i],h[n-i+1]);
fo(i,1,n)h[i]=max(h[i],h1[i]),swap(f[n-i+1],g[i]);
fo(i,1,n/2)swap(a[i],a[n-i+1]);
read(m);
fo(i,1,m)
{
read(q),read(w);
printf("%lld\n",max(g[q+1]+f[q-1],h[q]+(LL)a[q]-(LL)w));
}
return 0;
}