CodeForces 984D D. XOR-pyramid (区间DP)

D. XOR-pyramid
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

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 lr (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序列,有q次询问;每次询问区间[L,R]内最大的f(x)是多少?

f(x)的含义:F(x)表示x个数在规定运算下的值; 
当x=1时,F( 1 ) = a[1];f(1)表示只有一个数,此时f(x)就等于那个值; 
当x>1时,F( x ) = F( b[1]^b[2], b[2]^b[3] … b[x-1]^b[x] ); 表示 x 个数的f值;

题目给了组解释: 
 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 

画个图理解一下: 
这里写图片描述 
 此区间有5个数,用F[1][5]表示,从图中最后一步可以得出规律: 
  F[1][5]=F[1][4]^F[2][5];

剩下的就是一个区间dp了, 枚举长度,枚举起点,只不过这个不必枚举k了, 因为最后的转移式已经知道了

#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
const int maxn = 5e3 + 5;
int f[maxn][maxn], dp[maxn][maxn], a[maxn];
int main()
{
    int n, q;
    while(~scanf("%d", &n))
    {
        memset(dp, 0, sizeof(dp));
        memset(f, 0, sizeof(f));
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]), f[i][i] = a[i], dp[i][i] = a[i];
        for(int len = 1; len <= n; len++)
        {
            for(int l = 1; l+len <= n; l++)
            {
                int r = l + len;
                f[l][r] = f[l+1][r] ^ f[l][r-1];
                dp[l][r] = max(f[l][r], max(dp[l+1][r], dp[l][r-1]));
            }
        }
        int q;
        cin >> q;
        while(q--)
        {
            int l, r;
            scanf("%d%d", &l, &r);
            printf("%d\n", dp[l][r]);
        }
    }
    return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_34374664/article/details/80938924
今日推荐