CF#483 Div2 D. XOR-pyramid
? 解题记录 ? ? Codeforces ? ? 动态规划 ?    2018-09-13 22:57:18    497    0    0

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

f(b)={b[1]if m=1f(b[1]b[2],b[2]b[3],,b[m1]b[m])otherwise,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(12,24,48)=f(3,6,12)=f(36,612)=f(5,10)=f(510)=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 (1n50001≤n≤5000) — the length of aa.

The second line contains nn integers a1,a2,,ana1,a2,…,an (0ai23010≤ai≤230−1) — the elements of the array.

The third line contains a single integer qq (1q1000001≤q≤100000) — the number of queries.

Each of the next qq lines contains a query represented as two integers llrr (1lrn1≤l≤r≤n).

Output

Print qq lines — the answers for the queries.

Examples
input
Copy
38 4 122 31 2
output
Copy
512
input
Copy
61 2 4 8 16 3241 62 53 41 2
output
Copy
6030123
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].

 

题目大意:称这样的步骤为一次操作:把一个数组中的相邻两数两两依次的异或值拿来代替原数组,这样数组大小会减小1,重复这个步骤直到只剩一个数时,操作结束。给定一个数组,每次询问l,r之间的所有子区间拿来做这个操作后得到的最大值是多少。

可以看出每一个数在答案中被异或的次数就是组合数,这样求对2取模的组合数可以做到O(n^3)。

做题的时候智障了,其实杨辉三角上一层错位相加就等于下一层。所以假设[l,r]操作后结果为f[l,r],那么f[l,r]=f[l,r-1]^f[l+1,r]。这样就可以O(n^2)递推了,再用同样的方法就可以处理出子区间的最大值。

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn = 5e3 + 5;
int dp[maxn][maxn], mx[maxn][maxn];
int n, m, a[maxn], l, r;

int DP(int l, int r) {
	if(l == r) return a[l];
	if(~dp[l][r]) return dp[l][r];
	return dp[l][r] = DP(l, r - 1) ^ DP(l + 1, r);
}

int MX(int l, int r) {
	if(l == r) return a[l];
	if(~mx[l][r]) return mx[l][r];
	return mx[l][r] = max(max(MX(l, r - 1), MX(l + 1, r)), DP(l, r));
}

int main() {
	memset(dp, -1, sizeof(dp));
	memset(mx, -1, sizeof(mx));
	scanf("%d", &n);
	for(register int i = 1; i <= n; ++i)
		scanf("%d", &a[i]);
	scanf("%d", &m);
	for(register int i = 1; i <= m; ++i) {
		scanf("%d%d", &l, &r);
		printf("%d\n", MX(l, r));
	}
	return 0;
}

 

 

 

上一篇: UOJ#396. 【NOI2018】屠龙勇士

下一篇: CF Educational Codeforces Round 50 C. Classy Numbers

497 人读过
立即登录, 发表评论.
没有帐号? 立即注册
0 条评论
文档导航