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 <bits/stdc++.h>
#define pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;
const int K = 19;
int n, m;
vector<vector<int>> v;
vector<int> anc[K];
vector<int> depth;
int get_anc(int nd, int h){
for(int i = 0; i < K; i++) { if(h%2 == 1) nd = anc[i][nd]; h/=2; } return nd;
}
int lca_jump(int a, int b){
if(a == b) return a;
for(int i = K-1; i >= 0; i--) if(anc[i][a] != anc[i][b])
return lca_jump(anc[i][a], anc[i][b]);
return anc[0][a];
}
int lca(int a, int b){
if(depth[a] > depth[b]) swap(a, b);
b = get_anc(b, depth[b]-depth[a]);
return lca_jump(a, b);
}
void pre_dfs(int nd, int ss, int d){
for(int x: v[nd]) if(x != ss) pre_dfs(x, nd, d+1);
if(ss != -1) anc[0][nd] = ss;
depth[nd] = d;
}
vector<vector<tuple<int, int, ll>>> plans;
vector<ll> dp, childsum;
void dfs(int nd, int ss){
for(int x: v[nd]) if(x != ss) dfs(x, nd);
for(int x: v[nd]) if(x != ss) childsum[nd]+=dp[x];
dp[nd] = childsum[nd];
for(auto [a, b, c]: plans[nd]){
ll cur = c;
int _a = a, _b = b;
while(_a != nd) cur+=childsum[_a], _a = anc[0][_a];
while(_b != nd) cur+=childsum[_b], _b = anc[0][_b];
cur+=childsum[nd];
_a = a, _b = b;
while(_a != nd) cur-=dp[_a], _a = anc[0][_a];
while(_b != nd) cur-=dp[_b], _b = anc[0][_b];
dp[nd] = max(dp[nd], cur);
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
v.assign(n, {});
fill(anc, anc+K, vector<int>(n, 0));
depth.assign(n, -1);
plans.assign(n, {});
dp.assign(n, 0);
childsum.assign(n, 0);
for(int i = 0; i < n-1; i++){
int a, b; cin >> a >> b; a--, b--;
v[a].pb(b);
v[b].pb(a);
}
pre_dfs(0, -1, 0);
for(int p = 1; p < K; p++) for(int i = 0; i < n; i++)
anc[p][i] = anc[p-1][anc[p-1][i]];
cin >> m;
for(int i = 0; i < m; i++){
int a, b; ll c; cin >> a >> b >> c; a--, b--;
plans[lca(a, b)].pb({a, b, c});
}
dfs(0, -1);
cout << dp[0] << "\n";
}
# | 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... |