题目是要求动态的树上带权重心。
考虑一个重要结论:当前以 为根,如果 儿子 作为带权重心不如 优, 子树内的点也一定不如 优。(容易知道比 优的 不超过 )。
尝试证明。
设 表示 子树内的军队个数。
当前以 为根。假如带权重心从 移到儿子 ,答案产生的变化为 。如果 ,说明 更优。
仍然以 为根,假如带权重心从 移到 ,。若 ,必有 ,同时就有 。
因此若能从 移到 ,必定可以从 移到 。这样归纳一下即可得证。
那么我们可以考虑用这样的方法求树上的带权重心:
从根出发,考察他所有儿子作为带权重心时的答案,如果存在一个儿子比它优秀,移到该儿子上;否则当前点就是整棵树的带权重心。
这种算法显然与深度有关,考虑用点分树进行优化:
从根出发,考察他所有原树儿子作为带权重心的答案,如果更优秀,移到该儿子子树的重心(注意不是带权重心)上;否则停止。
正确性由前面的结论可知。实质上我们把原树上的挪动分治成了点分树上的挪动,深度是 的。
现在还有一个问题:如何快速计算带权重心的答案呢?
可以对于每个点记录三个值:
-
表示 的点分树子树内的军队个数。
-
表示 作为带权重心时, 的点分树子树内所有点对答案的贡献。
-
表示 点分树上父亲作为带权重心时, 的点分树子树内所有点对答案的贡献。
之后就很容易了,要算 的答案的话,从 开始一直跳点分树的父亲,同时计算即可。
这样单次修改复杂度 ,单次询问复杂度 ,其中 ,可以通过本题。
Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,q;
vector<pair<int,int>>edge[100005];
namespace LCA{
int depth[100005],st[200005][20],timer,in[100005],lg[200005];
void dfs(int id,int from){
st[in[id]=++timer][0]=id;
for(auto v:edge[id])if(v.first!=from){
depth[v.first]=depth[id]+v.second;
dfs(v.first,id);
st[++timer][0]=id;
}
}
inline void init(){
lg[0]=-1;
for(int i=1;i<=timer;i++)lg[i]=lg[i>>1]+1;
for(int len=1;len<=lg[timer];len++)
for(int i=1;i+(1<<len)-1<=timer;i++){
int a=st[i][len-1],b=st[i+(1<<(len-1))][len-1];
st[i][len]=(depth[a]<depth[b]?a:b);
}
}
inline int lca(int u,int v){
u=in[u],v=in[v];
if(u>v)swap(u,v);
int len=v-u+1,a=st[u][lg[len]],b=st[v-(1<<lg[len])+1][lg[len]];
return depth[a]<depth[b]?a:b;
}
inline int dist(int u,int v){return depth[u]+depth[v]-(depth[lca(u,v)]<<1);}
}using namespace LCA;
namespace G_tree{
int sz[100005],mxsz[100005],G,root,fa[100005],sum[100005];
ll dp[100005],fadp[100005];
bool vis[100005];
vector<int>e[100005];
void getG(int id,int from,int tot){
sz[id]=mxsz[id]=1;
for(auto v:edge[id])if(v.first!=from&&!vis[v.first]){
getG(v.first,id,tot);
sz[id]+=sz[v.first];
mxsz[id]=max(mxsz[id],sz[v.first]);
}mxsz[id]=max(mxsz[id],tot-sz[id]);
if(mxsz[G]>mxsz[id])G=id;
}
void divide(int id){
vis[id]=1;
for(auto v:edge[id])if(!vis[v.first]){
G=0,getG(v.first,id,sz[v.first]);
e[fa[G]=id].emplace_back(G);
divide(G);
}
}
void update(int id,int from,int e){
sum[id]+=e;
dp[id]+=1ll*e*dist(id,from);
if(fa[id]){
fadp[id]+=1ll*e*dist(fa[id],from);
update(fa[id],from,e);
}
}
int find(int id,int f){return fa[id]==f?id:find(fa[id],f);}
inline ll calc(int id,int from){
if(!id)return 0;
ll res=dp[id];
if(fa[id])res+=1ll*dist(fa[id],from)*(sum[fa[id]]-sum[id])-fadp[id];
return res+calc(fa[id],from);
}
ll query(int id){
ll tmp=calc(id,id);
for(auto v:edge[id])if(calc(v.first,v.first)<tmp)
return query(find(v.first,id));
return tmp;
}
}using namespace G_tree;
int main(){
scanf("%d%d",&n,&q);
for(int i=1,a,b,c;i<n;i++){
scanf("%d%d%d",&a,&b,&c);
edge[a].emplace_back(b,c);
edge[b].emplace_back(a,c);
}mxsz[0]=0x3f3f3f3f;
dfs(1,0),init();
getG(1,0,n),divide(root=G);
while(q--){
int u,e;
scanf("%d%d",&u,&e);
update(u,u,e);
printf("%lld\n",query(root));
}return 0;
}