Hướng dẫn giải của Arcade Game
Chỉ dùng lời giải này khi không có ý tưởng, và đừng copy-paste code từ lời giải này. Hãy tôn trọng người ra đề và người viết lời giải.
Nộp một lời giải chính thức trước khi tự giải là một hành động có thể bị ban.
Nộp một lời giải chính thức trước khi tự giải là một hành động có thể bị ban.
#include<bits/stdc++.h> #define ll long long #define ntr "\n" #define mod (ll)(1e9+7) #define taskname "" #define frep freopen(taskname".inp","r",stdin); freopen(taskname".out","w",stdout); using namespace std; vector<ll> euler(200009),pos(200009),sz(200009),sum(200009),fenwick(200009),depth(200009); ll up[200009][20]; vector<pair<ll,ll>> adj[200009]; ll n,q,p=1; struct edge{ ll a,b,w; }; vector<edge> edges; void dfs(ll u,ll par,ll w){ euler[p]=u; depth[u]=depth[par]+1; pos[u]=p; sz[u]=1; p++; up[u][0]=par; for(int i=1;i<20;i++){ up[u][i]=up[up[u][i-1]][i-1]; } sum[pos[u]]=sum[pos[par]]+w; for(auto [v,wi]:adj[u]){ if(v!=par){ dfs(v,u,wi); sz[u]+=sz[v]; } } } ll lca(ll u,ll v){ if(depth[u]<depth[v]) swap(u,v); ll k=depth[u]-depth[v]; for(int i=19;i>=0;i--){ if(k&(1<<i)){ u=up[u][i]; } } if(u==v){ return u; } for(int i=19;i>=0;i--){ if(up[u][i]!=up[v][i]){ u=up[u][i]; v=up[v][i]; } } return up[u][0]; } void update(ll u,ll val){ for(;u<=n;u+=u&(-u)){ fenwick[u]+=val; } } ll get(ll u){ ll s=0; for(;u>0;u-=u&(-u)){ s+=fenwick[u]; } return s; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); //frep; cin>>n; for(int i=0;i<n-1;i++){ ll a,b,w; cin>>a>>b>>w; edges.push_back({a,b,w}); adj[a].push_back({b,w}); adj[b].push_back({a,w}); } dfs(1,0,0); cin>>q; while(q--){ ll k,i,j; cin>>k>>i>>j; if(k==2){ ll k=lca(i,j); cout<<sum[pos[i]]+get(pos[i])+sum[pos[j]]+get(pos[j])-2*(sum[pos[k]]+get(pos[k]))<<ntr; } else{ ll delta=j-edges[i-1].w; ll a; if(depth[edges[i-1].a]>depth[edges[i-1].b]) a=edges[i-1].a; else a=edges[i-1].b; update(pos[a],delta); update(pos[a]+sz[a],-delta); edges[i-1].w=j; } } }
Bình luận