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.
38 4 122 31 2
512
61 2 4 8 16 3241 62 53 41 2
6030123
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; }
没有帐号? 立即注册