Codeforces 984 D - XOR-pyramid

D - XOR-pyramid

思路:

区间dp

dp[l][r]表示ƒ([l, r])的值

显然,状态转移方程为dp[l][r] = dp[l][r-1] ^ dp[l+1][r]

初始状态dp[i][i] = a[i]

可是,这道题求的是这段区间包含的某一连续区间的最大值

那么用差不多的转移方程再求一遍区间最大值:dp[l][r] = max(dp[l][r],dp[l][r-1],dp[l+1][r])

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long 
#define pb push_back
#define mem(a, b) memset(a, b, sizeof(a))

const int N = 5e3 + 5;
int dp[N][N], a[N];
int main() {
    int n, q, l, r;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    for (int i = n; i >= 1; i--) {
        dp[i][i] = a[i];
        for (int j = i+1; j <= n; j++) {
            dp[i][j] = dp[i][j-1] ^ dp[i+1][j];
        }
    }
    for (int i = n; i >= 1; i--) {
        for (int j = i+1; j <= n; j++) {
            dp[i][j] = max(dp[i][j], max(dp[i][j-1], dp[i+1][j]));
        }
    }
    scanf("%d", &q);
    while(q--) {
        scanf("%d %d", &l, &r);
        printf("%d\n", dp[l][r]);
    }
    return 0;
}

 

posted @ 2018-05-16 13:29  Wisdom+.+  阅读(325)  评论(0编辑  收藏  举报