1. 程式人生 > >Codeforces 984 D - XOR-pyramid

Codeforces 984 D - XOR-pyramid

\n push_back ace 方程 nbsp mes 區間 () n)

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; }

Codeforces 984 D - XOR-pyramid