#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (int i=a;i<=b;i++)
#define rep2(i,a,b,c) for (int i=a;i<=b;i+=c)
#define rev(i,a,b) for (int i=a;i>=b;i--)
#define rev2(i,a,b,c) for (int i=a;i>=b;i-=c)
#define bit(i,j) ((i>>j)&1)
#define pii pair<int,int>
#define ull unsigned long long
#define pb push_back
#define pf push_front
#define ll long long
#define Fi first
#define Se second
#define sz(a) (ll)(a.size())
#define on(n) __builtin_popcountll(n)
#define ld long double
#define __log2(x) 31-__builtin_clz(x)
#define Mask(x) (1LL<<x)
#define ALL(v) v.begin(),v.end()
const int MAXN=1e5+5;
const int mod=998244353;
struct node{
int u,v,w;
};
int n,u,v,m,a,b,c;
int up[MAXN][25],h[MAXN],dp[MAXN];
vector<int> g[MAXN];
vector<node> Path[MAXN];
void dfs(int u){
for (int v:g[u]){
if (v==up[u][0]) continue;
up[v][0]=u;
h[v]=h[u]+1;
rep(i,1,20) up[v][i]=up[up[v][i-1]][i-1];
dfs(v);
}
}
int calc(int cur,int u){
int sum=0;
int prev=0;
while(cur!=u){
for (int v:g[cur]){
if (v==prev||v==up[cur][0]) continue;
sum+=dp[v];
}
prev=cur;
cur=up[cur][0];
}
return sum;
}
int lca(int u,int v){
if (h[u]<h[v]) swap(u,v);
int k=h[u]-h[v];
rep(i,0,__log2(k))
if (bit(k,i)) u=up[u][i];
if (u==v) return u;
k=__log2(h[u]);
rev(i,k,0)
if (up[u][i]!=up[v][i])
u=up[u][i],v=up[v][i];
return up[u][0];
}
int jump(int u,int k){
int cur=u;
rep(i,0,__log2(k))
if (bit(k,i)) cur=up[cur][i];
return cur;
}
void calcdp(int u){
for (int v:g[u]){
if (v==up[u][0]) continue;
calcdp(v);
}
int sum=0;
for (int v:g[u]) sum+=dp[v];
dp[u]=max(dp[u],sum);
if (!Path[u].empty()){
for (node tmp:Path[u]){
int sum=calc(tmp.u,u)+calc(tmp.v,u);
int A=jump(tmp.u,h[tmp.u]-h[u]-1);
int B=jump(tmp.v,h[tmp.v]-h[u]-1);
for (int v:g[u]){
if (v==A||v==B||v==up[u][0]) continue;
sum+=dp[v];
}
dp[u]=max(dp[u],sum+tmp.w);
}
}
}
void solution(){
cin >> n;
rep(i,1,n-1){
cin >> u >> v;
g[u].pb(v);
g[v].pb(u);
}
dfs(1);
cin >> m;
rep(i,1,m){
cin >> a >> b >> c;
int x=lca(a,b);
Path[x].pb({a,b,c});
}
calcdp(1);
cout << dp[1];
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int test=1;
while(test--)
solution();
}
# | 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... |