P3097 [USACO13DEC] Optimal Milking G
可以看做序列上的动态 DP,给了我们思想上的启发
考虑无修改的情况,\(dp_{i,0/1}\) 表示到第 \(i\) 个数,选/不选它的最大值
接下来考虑有修改,发现记录一个区间左端点选/不选,右端点选/不选的最大值即可合并,因为这个合并过程具有结合律,因此可以用线段树维护之,时间复杂度 \(O(q\log n)\)
注意这个词:结合律
动态 DP 的实现就完全依赖结合律,这也是它常用矩阵转移原因
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
#define YUANSHEN ios_base::sync_with_stdio(0);
#define QIDONG cin.tie(0);
#define inf 1e14
using namespace std;
const int maxn=1e6+10;
int M[maxn],d,n,ans=0;
struct Tree{
struct node{int L,R,s[2][2];}tr[maxn*4];
void pushup(int u){
tr[u].s[1][1]=max({tr[u*2].s[1][0]+tr[u*2+1].s[0][1],tr[u*2].s[1][1]+tr[u*2+1].s[0][1],tr[u*2].s[1][0]+tr[u*2+1].s[1][1]});
tr[u].s[1][0]=max({tr[u*2].s[1][0]+tr[u*2+1].s[0][0],tr[u*2].s[1][1]+tr[u*2+1].s[0][0],tr[u*2].s[1][0]+tr[u*2+1].s[1][0]});
tr[u].s[0][1]=max({tr[u*2].s[0][1]+tr[u*2+1].s[0][1],tr[u*2].s[0][0]+tr[u*2+1].s[0][1],tr[u*2].s[0][0]+tr[u*2+1].s[1][1]});
tr[u].s[0][0]=max({tr[u*2].s[0][1]+tr[u*2+1].s[0][0],tr[u*2].s[0][0]+tr[u*2+1].s[1][0],tr[u*2].s[0][0]+tr[u*2+1].s[0][0]});
}
void build(int u,int l,int r){
tr[u].L=l; tr[u].R=r;
if(l==r){tr[u].s[1][1]=M[l]; tr[u].s[0][1]=tr[u].s[1][0]=-inf; return;}
int mid=(l+r)>>1;
build(u*2,l,mid); build(u*2+1,mid+1,r);
pushup(u);
}
void update(int u,int x,int k){
if(tr[u].L==tr[u].R){tr[u].s[1][1]=k; return;}
if(tr[u*2].R>=x)update(u*2,x,k);
else update(u*2+1,x,k);
pushup(u);
}
int query(){return max({tr[1].s[0][0],tr[1].s[1][1],tr[1].s[1][0],tr[1].s[0][1]});}
}T;
signed main(){
YUANSHEN QIDONG
cin>>n>>d;
for(int i=1;i<=n;i++)cin>>M[i];
T.build(1,1,n);
while(d--){
int i,m; cin>>i>>m;
T.update(1,i,m); ans+=T.query();
}
cout<<ans;
return 0;
}

浙公网安备 33010602011771号