dp - 求连续区间异或的最大值
For an array b of length m we define the function f
as
where ⊕
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)=15
You are given an array a
and a few queries. Each query is represented as two integers l and r. The answer is the maximum value of f on all continuous subsegments of the array al,al+1,…,ar
.
The first line contains a single integer n
(1≤n≤5000) — the length of a
.
The second line contains n
integers a1,a2,…,an (0≤ai≤230−1
) — the elements of the array.
The third line contains a single integer q
(1≤q≤100000
) — the number of queries.
Each of the next q
lines contains a query represented as two integers l, r (1≤l≤r≤n
).
Print q
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]
, for second query — [2,5], for third — [3,4], for fourth — [1,2
题意 : 给你n 个数和一些询问,询问所给区间连续的一段函数异或下来的值最大。
思路分析:打比赛的时候题都没读明白,想了一个线性基,然后结果题读错了,题目是让求异或函数的最大值,然后 g 了,第二天看了看大佬们的讨论,才知道原来是个 dp,先预处理出来所有区间的异或函数值,然后dp搞一下就可以。
代码示例:
int a[5005]; int f[5005][5005], dp[5005][5005]; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n; cin >> n; for(int i = 1; i <= n; i++){ scanf("%d", &a[i]); f[i][i] = dp[i][i] = a[i]; } //for(int len = 2; len <= n; len++){ //for(int i = 1; i <= n; i++){ //int j = i+len-1; //if (j > n) break; //f[i][j] = f[i][j-1]^f[i+1][j]; //} //} for(int len = 2; len <= n; len++){ for(int i = 1; i <= n; i++){ int j = i+len-1; if (j > n) break; dp[i][j] = max(f[i][j] = f[i][j-1]^f[i+1][j], max(dp[i][j-1], dp[i+1][j])); } } int q; int l, r; cin >> q; while(q--){ scanf("%d%d", &l, &r); printf("%d\n", dp[l][r]); } return 0; }
打比赛的时候题都没读明白,想了一个线性基,然后结果题读错了,题目是让求异或函数的最大值,然后 g 了,第二天看了看大佬们的讨论,才知道原来是个 dp,先预处理出来所有区间的异或函数值,然后dp搞一下就可以。