动态 dp 卡常
EnofTaiPeople · · 题解
这是一道被埋没了的卡常好题,与其说它卡了树剖和 LCT,倒不如说它卡了较慢的输出方式。
如何解决动态树最大权独立集?设节点
于是有了以下转移:
可以转换成矩阵乘法,具有交换律,用 LCT 维护即可。
不过这都不是重点,因为本题用 LCT 不加优化过不了!
真的是因为 LCT 太慢吗?要跑三秒多?
其实 printf 输出就用了一秒多。
于是有了快读快写,有了它们,再也不怕卡常啦!
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+6,I_F=-1e9;
namespace fast_io{
char buf[N+5],*p1,*p2,c;
#define gc (p1==p2&&(p2=(p1=buf)+fread(buf,1,N,stdin),p1==p2)?EOF:*p1++)
inline int read(){
int an=0,f=1;while(!isdigit(c=gc))if(c=='-')f=-f;
do an=an*10+(48^c);while(isdigit(c=gc));return an*f;
}
int ot;
char ob[N+20],stk[20],t;
inline void fls(){
fwrite(ob,1,ot,stdout),ot=0;
}
inline void write(int x){
if(x<0)ob[ot++]='-',x=-x;
while(x>9)stk[++t]=48^(x%10),x/=10;
for(ob[ot++]=48^x;t;ob[ot++]=stk[t--]);
ob[ot++]='\n';
if(ot>N)fls();
}
}
using fast_io::read;
using fast_io::write;
int n,q,t[N][2],f[N],aw[N],las;
vector<int>lk[N];
struct Mtx{
int a[2][2];
}v[N],sm[N];
inline void max_to(int &x,int y){if(x<y)x=y;}
inline Mtx operator*(const Mtx &x,const Mtx &y){
Mtx z={{{x.a[0][0]+y.a[0][0],x.a[0][0]+y.a[0][1]},
{x.a[1][0]+y.a[0][0],x.a[1][0]+y.a[0][1]}}};
for(int i=0;i<=1;++i)
for(int j=0;j<=1;++j)
max_to(z.a[i][j],x.a[i][1]+y.a[1][j]);
return z;
}
void dfs(int x){
for(int y:lk[x])
if(y!=f[x]){
f[y]=x,dfs(y),v[x].a[1][0]+=v[y].a[0][0];
v[x].a[0][0]+=max(v[y].a[0][0],v[y].a[1][0]);
}v[x].a[0][1]=v[x].a[0][0];
v[x].a[1][1]=I_F,sm[x]=v[x];
}
#define Tp(x) (t[f[x]][1]==x)
#define In(x) (Tp(x)||t[f[x]][0]==x)
#define rs t[x][1]
inline void pp(int x){
sm[x]=v[x];
if(t[x][0])sm[x]=sm[t[x][0]]*sm[x];
if(rs)sm[x]=sm[x]*sm[rs];
}
inline void rot(int x){
int y=f[x],k=Tp(x),w=t[x][!k];
f[t[t[x][!k]=y][k]=w]=y;
if(In(y))t[f[y]][Tp(y)]=x;
f[x]=f[y],f[y]=x,pp(y);
}
inline void splay(int x){
for(int y=f[x];In(x);rot(x),y=f[x])
if(In(y))rot(Tp(x)^Tp(y)?x:y);
}
inline void access(int x){
for(int y=0;x;x=f[y=x]){
if(splay(x),rs){
v[x].a[0][0]+=max(sm[rs].a[0][0],sm[rs].a[1][0]);
v[x].a[1][0]+=sm[rs].a[0][0];
}if(y){
v[x].a[0][0]-=max(sm[y].a[0][0],sm[y].a[1][0]);
v[x].a[1][0]-=sm[y].a[0][0];
}v[x].a[0][1]=v[x].a[0][0],rs=y,pp(x);
}
}
int main(){
n=read(),q=read();int i,x,y;
for(x=1;x<=n;++x)v[x].a[1][0]=aw[x]=read();
for(i=1;i<n;++i){
x=read(),y=read();
lk[x].push_back(y);
lk[y].push_back(x);
}dfs(1);
while(q--){
x=read()^las,access(x),splay(x);
v[x].a[1][0]-=aw[x];
v[x].a[1][0]+=(aw[x]=read()),pp(x);
write(las=max(sm[x].a[0][0],sm[x].a[1][0]));
}fast_io::fls();
return 0;
}