HDU-5805-NanoApe Loves Sequence RMQ
NanoApe, the Retired Dog, has returned back to prepare for the National Higher Education Entrance Examination!
In math class, NanoApe picked up sequences once again. He wrote down a sequence with nn numbers on the paper and then randomly deleted a number in the sequence. After that, he calculated the maximum absolute value of the difference of each two adjacent remained numbers, denoted as FF.
Now he wants to know the expected value of FF, if he deleted each number with equal probability.
Input
The first line of the input contains an integer TT, denoting the number of test cases.
In each test case, the first line of the input contains an integer nn, denoting the length of the original sequence.
The second line of the input contains nn integers A1,A2,...,AnA1,A2,...,An, denoting the elements of the sequence.
1≤T≤10, 3≤n≤100000, 1≤Ai≤1091≤T≤10, 3≤n≤100000, 1≤Ai≤109
Output
For each test case, print a line with one integer, denoting the answer.
In order to prevent using float number, you should print the answer multiplied by nn.
Sample Input
1
4
1 2 3 4
Sample Output
6
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int MAX=100005;
int stTable[MAX][32];
int preLog2[MAX];
int p[MAX];
int q[MAX];
int max(int a,int b)
{
return a>b?a:b;
}
void st_prepare(int n,int *array)
{
preLog2[1]=0;
for(int i=2; i<=n; i++)
{
preLog2[i]=preLog2[i-1];
if((1<<preLog2[i]+1)==i)
{
++preLog2[i];
}
}
for(int i=n-1; i>=0; --i)
{
stTable[i][0]=array[i];
for(int j=1; (i+(1<<j)-1)<n; j++)
{
stTable[i][j]=max(stTable[i][j-1],stTable[i+(1<<j-1)][j-1]);
}
}
}
int query_max(int l,int r)
{
if(r<l)
return 0;
int len=r-l+1,k=preLog2[len];
return max(stTable[l][k],stTable[r-(1<<k)+1][k]);
}
int max(int a,int b,int c)
{
return max(a,max(b,c));
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(q,0,sizeof(q));
memset(p,0,sizeof(p));
memset(stTable,0,sizeof(stTable));
memset(preLog2,0,sizeof(preLog2));
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&p[i]);
}
for(int i=0; i<n-1; i++)
{
q[i]=abs(p[i+1]-p[i]);
}
st_prepare(n-1,q);
long long sum=0;
for(int i=0; i<n; i++)
{
if(i==0)
sum+=query_max(1,n-2);
else if(i==n-1)
sum+=query_max(0,n-3);
else if(i==1)
sum+=max(query_max(2,n-2),abs(p[i+1]-p[i-1]));
else if(i==n-2)
sum+=max(query_max(0,i-2),abs(p[i+1]-p[i-1]));
else
sum+=max(query_max(0,i-2),query_max(i+1,n-2),abs(p[i+1]-p[i-1]));
}
printf("%lld\n",sum);
}
}