P3320 [SDOI2015]寻宝游戏(数剖+定理
作者:互联网
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=3e5+10;
struct node{
int nxt,to;ll val;
}d[N];int head[N],tot=0;
void add(int a,int b,ll c){
d[++tot]={head[a],b,c};head[a]=tot;
}
int fa[N][18],depth[N],dfn[N],rdfn[N],tt=0;ll val[N];
int n,q;
void dfs(int x,int f){
depth[x]=depth[f]+1;
fa[x][0]=f;
for(int i=1;i<18;i++){fa[x][i]=fa[fa[x][i-1]][i-1];}
for(int i=head[x];i;i=d[i].nxt){
int v=d[i].to;if(v==f) continue;
dfs(v,x);
}
}
int query(int a,int b){
if(depth[a]<depth[b]) swap(a,b);
for(int i=17;i>=0;i--){
if(depth[fa[a][i]]>=depth[b]) a=fa[a][i];
}
if(a==b) return a;
for(int i=17;i>=0;i--){
if(fa[a][i]!=fa[b][i]){
a=fa[a][i];b=fa[b][i];
}
}
return fa[a][0];
}
void dfs2(int x,int f){
dfn[x]=++tt;rdfn[tt]=x;
for(int i=head[x];i;i=d[i].nxt){
int to=d[i].to;if(to==f) continue;
val[to]+=d[i].val+val[x];
dfs2(to,x);
}
}
ll getdis(int a,int b){
int lcapos=query(a,b);
return -val[lcapos]*2+val[a]+val[b];
}
set<int> s;
int vis[N];
int main(){
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++) vis[i]=-1;
for(int i=1;i<=n-1;i++){
int x,y,z;scanf("%d%d%d",&x,&y,&z);
add(x,y,z);add(y,x,z);
}
dfs(1,0);dfs2(1,0);
ll ans=0;
// for(int i=1;i<=n;i++){
// cout<<dfn[i]<<endl;
// }
while(q--){
int y;scanf("%d",&y);
vis[y]=-vis[y];
// cout<<vis[y]<<endl;
// cout<<dfn[y]<<endl;
if(vis[y]==1){
int x=dfn[y];
s.insert(x);
auto pos=s.find(x);
int l,r;
if(pos==s.begin()){
l=*prev(s.end());
}else{
pos--;
l=*(pos);
}
pos=s.find(x);pos++;
if(pos==s.end()){
r=*(s.begin());
}else{
r=*pos;
}
l=rdfn[l],r=rdfn[r];
x=rdfn[x];
// cout<<l<<" "<<r<<endl;
ans+=getdis(x,l)+getdis(r,x)-getdis(l,r);
}else{
int x=dfn[y];
auto pos=s.find(x);
int l,r;
if(pos==s.begin()){
l=*prev(s.end());
}else{
pos--;
l=*(pos);
}
pos=s.find(x);pos++;
if(pos==s.end()){
r=*(s.begin());
}else{
r=*pos;
}
s.erase(x);
l=rdfn[l],r=rdfn[r];
x=rdfn[x];
// cout<<l<<" "<<r<<endl;
ans-=getdis(x,l)+getdis(r,x)-getdis(l,r);
}
cout<<ans<<endl;
}
}
标签:P3320,数剖,val,int,ll,pos,fa,SDOI2015,rdfn 来源: https://blog.csdn.net/weixin_45714303/article/details/121164004