D. XOR-pyramid (区间dp)

D. XOR-pyramid(区间dp)

time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
For an array b of length m we define the function f as

f(b)={b[1]f(b[1]⊕b[2],b[2]⊕b[3],…,b[m−1]⊕b[m])if m=1otherwise,
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)=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 (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).

Output
Print q lines — the answers for the queries.

Examples
inputCopy
3
8 4 1
2
2 3
1 2
outputCopy
5
12
inputCopy
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2
outputCopy
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].

题意 求 区间 l - r 内的 最大 f( a-b );
这题发现公式 就比较好写

dp[l][r]=dp[l+1][r]^dp[l][r-1];

一开始 以为只要求 dp[ l ][ r ] ,然后找到规律 就交了一发 结果 要求 子区间的 最大 dp[][];
然后就开始懵 了 好像不会求最大 难道要枚举每个子区间?
然后看了大佬的代码才知道 原来和求 dp[l][r]的步骤一样
区间长度为 len 的最大值只需要由 len-1 的转移过来就好了
代码

#include<iostream>
#include<cstdio>
#include<map>
#include<math.h>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=5e3+7;
const int mod=1e9+7;
ll dp[maxn][maxn];
int main (){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%lld",&dp[i][i]);
    }
    for(int len=2;len<=n;len++){
        for(int i=1;i+len-1<=n;i++){
            dp[i][i+len-1]=dp[i][i+len-1-1]^dp[i+1][i+len-1];
            //printf("%lld %d %d\n",dp[i][i+len-1],i,i+len-1);
        }
    }
     for(int len=2;len<=n;len++){
        for(int i=1;i+len-1<=n;i++){
            dp[i][i+len-1]=max(dp[i][i+len-1] ,max(dp[i][i+len-1-1],dp[i+1][i+len-1]));
            //printf("%lld %d %d\n",dp[i][i+len-1],i,i+len-1);
        }
    }
    int k;
    scanf("%d",&k);
    for(int i=0;i<k;i++){
        int l,r;
        scanf("%d%d",&l,&r);
        printf ("%lld\n",dp[l][r]);
    }



return 0;
}


发布了11 篇原创文章 · 获赞 1 · 访问量 391

猜你喜欢

转载自blog.csdn.net/hddddh/article/details/104957817