B. XOR-pyramid ( 记忆化dp )

  • 题目链接:http://codeforces.com/contest/983/problem/B
  • 题意:给你n个整数,输入q组询问,每组询问有两个整数l,r。输出 l~r 区间内任意连续范围的最大 f()
    • f(1,2, 3) = (1^2) ^ (2^3)
  • 算法:记忆化 dp
  • 思路:递归思想,令dp[0][i] = a[i],令dp[i][j] 为 第i层递归的第j个连续(i+1)个数的 f() 值,则再将dp[i][j] 更新为 dp[i][j] 、 dp[i-1][j] 、dp[i-1][j+1] 的最大值。则查找 l~r 的最大值时,只需要输出 dp[r-l][l-1] 即可
  • 这里写图片描述

#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const LL ll_INF = 1LL<<62;
const int maxn = 5000 + 10;
const int mod = 1e9 + 7;

int n;
int a[maxn], dp[maxn][maxn];

void init()
{
    for(int i=0; i<n; i++) dp[0][i] = a[i];
    for(int i=1; i<n; i++){
        for(int j=0; j<n-i; j++){
            dp[i][j] = dp[i-1][j] ^ dp[i-1][j+1];
        }
    }
    for(int i=1; i<n; i++){
        for(int j=0; j<n-i; j++){
            dp[i][j] = max(dp[i][j], dp[i-1][j]);
            dp[i][j] = max(dp[i][j], dp[i-1][j+1]);
        }
    }
}

int main()
{
    scanf("%d", &n);
    for(int i=0; i<n; i++) scanf("%d", &a[i]);
    init();
    int q; scanf("%d", &q);
    while(q--)
    {
        int l, r;
        scanf("%d%d", &l, &r);
        printf("%d\n", dp[r-l][l-1]);
    }
}
/*
3
8 4 1
2
2 3
1 2
*/

猜你喜欢

转载自blog.csdn.net/qq_37352710/article/details/80480978