In fact, the whole chain is folded in half to get a tree. Also using a multiplier table, consider maintaining four values: Max,min,premax,submax, which can be solved.
You can also use the line segment tree: The principal update and multiplication method are the same, and the same four values are recorded in each interval. Tip: Return a struct directly on return.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define MAXN 200005
using namespace Std;
Long Long n,ma[maxn][30],mi[maxn][30],m,x,y,price[maxn],submax[maxn][30],premax[maxn][30];
Long Long anc[maxn][30];
Long long ask (long long x,long long y)
{
Long Long minn=55667788,ans=0,maxnn=0;
if (x<y)
{
For (Long long i=25;i>=0;i--)
{
if (x+ (1<<i) <=y)
{
Ans=max (Submax[x][i],ans);
Ans=max (Ans,ma[x][i]-minn);
Minn=min (Minn,mi[x][i]);
X=anc[x][i];
}
}
}
Else
{
Swap (x, y);
For (Long long i=25;i>=0;i--)
{
if (Y (1<<i) >=x)
{
Ans=max (Premax[x][i],ans);
Ans=max (Ans,maxnn-mi[x][i]);
Maxnn=max (Maxnn,ma[x][i]);
X=anc[x][i];
}
}
}
return ans;
}
int main ()
{
scanf ("%lld", &n);
For (Long long i=1;i<=n;i++)
scanf ("%lld", &price[i]);
For (Long long i=1;i<=n;i++)
{
anc[i][0]=i+1;
Ma[i][0]=max (price[i],price[i+1]);
Mi[i][0]=min (price[i],price[i+1]);
Submax[i][0]=price[i+1]-price[i];
PREMAX[I][0]=PRICE[I]-PRICE[I+1];
}
For (Long long e=1;e<=25;e++)
For (Long long i=1;i<=n;i++)
{
Ma[i][e]=max (ma[i][e-1],ma[anc[i][e-1]][e-1]);
Mi[i][e]=min (mi[i][e-1],mi[anc[i][e-1]][e-1]);
Submax[i][e]=max (Max (submax[i][e-1],submax[anc[i][e-1]][e-1]), ma[anc[i][e-1]][e-1]-mi[i][e-1]);
Premax[i][e]=max (Max (premax[i][e-1],premax[anc[i][e-1]][e-1]), ma[i][e-1]-mi[anc[i][e-1]][e-1]);
ANC[I][E]=ANC[ANC[I][E-1]][E-1];
}
scanf ("%lld", &m);
For (Long long i=1;i<=m;i++)
{
scanf ("%lld%lld", &x,&y);
if (x==y) printf ("0\n");
else printf ("%lld\n", ask (x, y));
}
return 0;
}
Codevs 3304 fruit elder sister stroll Fruit Street One