This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <vector>
using namespace std;
const int maxn=1e5+7;
int n,m;
int par[maxn],lv[maxn],f[maxn][18];
int in[maxn],out[maxn],bit[maxn],dp[maxn];
vector<int> adj[maxn],road[maxn];
struct Query{int a,b,c;}q[maxn];
inline void Dfs(const int &u,const int &p){
static int nVisit=0;
in[u]=++nVisit;
par[u]=p;
lv[u]=lv[p]+1;
f[u][0]=p;
for(int i=1;i<18;i++) f[u][i]=f[f[u][i-1]][i-1];
for(int v: adj[u]) if(v!=p) Dfs(v,u);
out[u]=nVisit;
}
inline int Jump(int u,int k){
for(int cur=0;k;k>>=1,cur++) if(k&1) u=f[u][cur];
return u;
}
inline int Lca(int u,int v){
if(lv[u]>lv[v]) swap(u,v);
v=Jump(v,lv[v]-lv[u]);
if(u==v) return u;
for(int i=17;i>=0;i--) if(f[u][i]!=f[v][i]) u=f[u][i],v=f[v][i];
return par[u];
}
inline void Update(int x,const int &val){
for(;x<=n;x+=x&-x) bit[x]+=val;
}
inline int Get(int x){
int res=0;
for(;x;x-=x&-x) res+=bit[x];
return res;
}
inline void Solve(const int &u,const int &p){
int sumChild=0;
for(int v: adj[u]) if(v!=p){
Solve(v,u);
sumChild+=dp[v];
}
dp[u]=sumChild;
for(int i: road[u]){
int a=q[i].a,b=q[i].b,c=q[i].c;
dp[u]=max(dp[u],sumChild+Get(in[a])+Get(in[b])+c);
}
Update(in[u],sumChild-dp[u]); Update(out[u]+1,dp[u]-sumChild);
}
int main(){
cin>>n;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Dfs(1,0);
cin>>m;
for(int i=1;i<=m;i++){
cin>>q[i].a>>q[i].b>>q[i].c;
road[Lca(q[i].a,q[i].b)].push_back(i);
}
Solve(1,0);
cout<<dp[1];
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |