dp - 求连续区间异或的最大值

For an array b of length m we define the function f

as

f(b)={b[1]if m=1f(b[1]b[2],b[2]b[3],,b[m1]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)=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

.

Input

The first line contains a single integer n

(1n5000) — the length of a

.

The second line contains n

integers a1,a2,,an (0ai2301

) — the elements of the array.

The third line contains a single integer q

(1q100000

) — the number of queries.

Each of the next q

lines contains a query represented as two integers l, r (1lrn

).

Output

Print q

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]

, 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搞一下就可以。

 

转载于:https://www.cnblogs.com/ccut-ry/p/9047652.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值