B. XOR-pyramid(类似杨辉三角区间dp)

https://codeforces.com/problemset/problem/983/B


For an array bb of length mm we define the function ff as

f(b)={b[1]f(b[1]⊕b[2],b[2]⊕b[3],…,b[m−1]⊕b[m])if m=1otherwise,f(b)={b[1]if m=1f(b[1]⊕b[2],b[2]⊕b[3],…,b[m−1]⊕b[m])otherwise,

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.

Input

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.

扫描二维码关注公众号,回复: 11631843 查看本文章

Each of the next qq lines contains a query represented as two integers ll, rr (1≤l≤r≤n1≤l≤r≤n).

Output

Print qq lines — the answers for the queries.

Examples

input

Copy

3
8 4 1
2
2 3
1 2

output

Copy

5
12

input

Copy

6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2

output

Copy

60
30
12
3

Note

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].


自己写的时候发现题意读错了。

题意:给f(l,r),有q个询问,每个询问[l,r]求最大的f[i,j],其中l<=i<=j<=r;

开始看着没什么思路。但是把题目给的式子给展开可以发现类似一个每一层的数量类似杨辉三角。

比如f(a1,a2,a3,a4)

=f(a1^a2,a2^a3,a3^a4)

=f(a1^a2^a2^a3,a2^a3^a3^a4)

=f(a1^a2^a2^a3^a2^a3^a3^a4)

=f(a1^a2^a3^a4)

所以可以看出最后一步的转移是dp[l][r]=dp[l][r-1]^dp[l+1][r]

然后要求里面转移过程中的最大值。用ans[l,r]=max(dp[l,r],ans[l][r-1],ans[l+1][r])更新

图源:https://www.cnblogs.com/mountaink/p/9536718.html

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e3+100;
typedef long long LL;
LL a[maxn],dp[maxn][maxn],ans[maxn][maxn];
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n;cin>>n;
  for(LL i=1;i<=n;i++) cin>>a[i];
  for(LL i=1;i<=n;i++) {
  	dp[i][i]=ans[i][i]=a[i];
  }
  for(LL len=2;len<=n;len++){
  	for(LL i=1;i+len-1<=n;i++){
		LL j=i+len-1;
		dp[i][j]=dp[i][j-1]^dp[i+1][j];
		ans[i][j]=max(dp[i][j],max(ans[i][j-1],ans[i+1][j]));  	
	}
  }
  LL q;cin>>q;
  while(q--){
  	LL l,r;cin>>l>>r;
  	cout<<ans[l][r]<<endl;
  }
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/108466620
今日推荐