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

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

题意:
f{b1,b2,b3…bn}的结果为一个杨辉三角的最顶端结果,底端是b1,b2,b3…
b1,b2的上层节点为b1 ^ b2, b2,b3的上层节点为b2 ^ b3。以此类推
求区间(l,r)的最大 f 子段

思路:
可以得出的结论是 b[i][j] = b[i + 1][j] ^ b[i][j - 1]。
那么定义f[i][j]为区间i到j的最大子段值,b[i][j]为子段i到j的杨辉异或值。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int a[5005];
int b[5005][5005],f[5005][5005];

int main()
{
    int n;scanf("%d",&n);
    for(int i = 1;i <= n;i++)
    {
        scanf("%d",&a[i]);
        b[i][i] = f[i][i] = a[i];
    }
    
    for(int len = 2;len <= n;len++)
    {
        for(int i = 1;i + len - 1 <= n;i++)
        {
            int j = i + len - 1;
            b[i][j] = b[i + 1][j] ^ b[i][j - 1];
            f[i][j] = max(b[i][j],max(f[i + 1][j],f[i][j - 1]));
        }
    }
    
    int q;scanf("%d",&q);
    while(q--)
    {
        int l,r;scanf("%d%d",&l,&r);
        printf("%d\n",f[l][r]);
    }
                          
    return 0;
}
发布了676 篇原创文章 · 获赞 18 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tomjobs/article/details/104230404
今日推荐