For an array bb of length mm we define the function ff as
where ⊕⊕ is bitwise exclusive OR.
For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6,6⊕12)=f(5,10)=f(5⊕10)=f(15)=15f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6,6⊕12)=f(5,10)=f(5⊕10)=f(15)=15
You are given an array aa and a few queries. Each query is represented as two integers ll and rr. The answer is the maximum value of ff on all continuous subsegments of the array al,al+1,…,aral,al+1,…,ar.
The first line contains a single integer nn (1≤n≤50001≤n≤5000) — the length of aa.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1) — the elements of the array.
The third line contains a single integer qq (1≤q≤1000001≤q≤100000) — the number of queries.
Each of the next qq lines contains a query represented as two integers ll, rr (1≤l≤r≤n1≤l≤r≤n).
Print qq lines — the answers for the queries.
3 8 4 1 2 2 3 1 2
5 12
6 1 2 4 8 16 32 4 1 6 2 5 3 4 1 2
60 30 12 3
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.
In second sample, optimal segment for first query are [3,6][3,6], for second query — [2,5][2,5], for third — [3,4][3,4], for fourth — [1,2][1,2].
作为一个dp黑洞我竟然又凭一己之力做了一道dp。。。xr[i][j]表示从i到j的区间对应的函数值,这个东西跟杨辉三角差不多的道理,推了一上午。。。mx[i][j]表示在i到j区间内,包含j的区间最大的函数值,f是我们要求的答案。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<cmath>
using namespace std;
int n,q;
int a[5010];
int xr[5010][5010],mx[5010][5010],f[5010][5010];
int main()
{
scanf("%d",&n);
for (int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
memset(xr,0,sizeof(xr));
for (int i=n; i>=1; i--)
{
xr[i][i]=a[i];
for (int j=i+1; j<=n; j++)
{
xr[i][j]=xr[i][j-1]^xr[i+1][j];
}
}
memset(mx,0,sizeof(mx));
for (int j=n; j>=1; j--)
{
mx[j][j]=xr[j][j];
for (int i=j-1; i>=1; i--)
{
mx[i][j]=max(mx[i+1][j],xr[i][j]);
}
}
memset(f,0,sizeof(f));
for (int i=1; i<=n; i++)
{
f[i][i]=xr[i][i];
for (int j=i+1; j<=n; j++)
{
f[i][j]=max(f[i][j-1],mx[i][j]);
}
}
scanf("%d",&q);
while (q--)
{
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",f[l][r]);
}
return 0;
}