【SP1716】GSS3 - Can you answer these queries III(动态DP)
题目链接
之前用线段树写了一遍,现在用\(ddp\)再写一遍。
#include <cstdio>
#define lc (now << 1)
#define rc (now << 1 | 1)
inline int max(int a, int b){
return a > b ? a : b;
}
const int INF = 2147483647 >> 2;
const int MAXN = 50010;
inline int read(){
int s = 0, w = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){ if(ch == '-') w = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); }
return s * w;
}
struct Matrix{
int a[3][3];
}sum[MAXN << 2];
int a[MAXN], n, m, A, B, opt;
inline Matrix operator * (Matrix a, Matrix b){
Matrix c;
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
c.a[i][j] = -INF;
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
for(int k = 0; k < 3; ++k)
c.a[i][j] = max(c.a[i][j], a.a[i][k] + b.a[k][j]);
return c;
}
inline void pushup(int now){
sum[now] = sum[lc] * sum[rc];
}
void build(int now, int l, int r){
if(l == r){
sum[now].a[0][0] = sum[now].a[0][2] = sum[now].a[1][0] = sum[now].a[1][2] = a[l];
sum[now].a[0][1] = sum[now].a[2][0] = sum[now].a[2][1] = -INF;
sum[now].a[1][1] = sum[now].a[2][2] = 0; return ;
}
int mid = (l + r) >> 1;
build(lc, l, mid); build(rc, mid + 1, r); pushup(now);
}
void modify(int now, int l, int r, int x, int y){
if(l == r){
sum[now].a[0][0] = sum[now].a[0][2] = sum[now].a[1][0] = sum[now].a[1][2] = y;
return ;
}
int mid = (l + r) >> 1;
if(x <= mid) modify(lc, l, mid, x, y);
else modify(rc, mid + 1, r, x, y);
pushup(now);
}
Matrix query(int now, int l, int r, int wl, int wr){
if(l >= wl && r <= wr) return sum[now];
int mid = (l + r) >> 1;
if(wl <= mid && wr > mid)
return query(lc, l, mid, wl, wr) * query(rc, mid + 1, r, wl ,wr);
else if(wl <= mid)
return query(lc, l, mid, wl, wr);
else return query(rc, mid + 1, r, wl, wr);
}
int main(){
n = read();
for(int i = 1; i <= n; ++i)
a[i] = read();
build(1, 1, n);
m = read();
for(int i = 1; i <= m; ++i){
opt = read(); A = read(); B = read();
if(opt){
Matrix ans = query(1, 1, n, A, B);
printf("%d\n", max(ans.a[1][0], ans.a[1][2]));
}
else modify(1, 1, n, A, B);
}
return 0;
}