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;
struct BIT{
int n;
vector<ll> sm;
BIT(){}
BIT(int _n){
n = _n;
sm.resize(n);
}
void add(int in, ll x){
in++;
while(in <= n) sm[in-1]+=x, in+=in&-in;
}
void add(int l, int r, ll x){
add(l, x);
if(r+1 < n) add(r+1, -x);
}
ll get(int in){
in++;
ll s = 0;
while(in >= 1) s+=sm[in-1], in-=in&-in;
return s;
}
};
int n, m;
vector<vector<int>> v;
vector<int> anc[K];
vector<int> depth;
vector<int> pos;
vector<int> sz;
int pos_cnt = 0;
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){
pos[nd] = pos_cnt++;
for(int x: v[nd]) if(x != ss) pre_dfs(x, nd, d+1);
for(int x: v[nd]) if(x != ss) sz[nd]+=sz[x];
if(ss != -1) anc[0][nd] = ss;
depth[nd] = d;
}
vector<vector<tuple<int, int, ll>>> plans;
vector<ll> dp, childsum;
BIT bit;
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;
cur+=bit.get(pos[a]);
cur+=bit.get(pos[b]);
cur-=2LL*bit.get(pos[nd]);
cur+=childsum[nd];
dp[nd] = max(dp[nd], cur);
}
bit.add(pos[nd], pos[nd]+sz[nd]-1, childsum[nd]-dp[nd]);
}
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);
pos.assign(n, -1);
sz.assign(n, 1);
plans.assign(n, {});
dp.assign(n, 0);
childsum.assign(n, 0);
bit = BIT(n);
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... |