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>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
#define arr3 array<int, 3>
struct FT{
vector<ll> bit;
int n;
FT(int ns){
n = ns;
bit.resize(n + 1);
}
void add(int v, ll x){
while (v <= n){
bit[v] += x;
v |= (v + 1);
}
}
void add(int l, int r, ll x){
add(l, x);
add(r + 1, -x);
}
ll get(int v){
ll out = 0;
while (v > 0){
out += bit[v];
v = (v & (v + 1)) - 1;
}
return out;
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n; cin>>n;
vector<int> g[n + 1];
for (int i = 1; i < n; i++){
int x, y; cin>>x>>y;
g[x].pb(y);
g[y].pb(x);
}
const int lg = log2(n);
vector<vector<int>> pw(n + 1, vector<int>(lg + 1));
vector<int> tin(n + 1), tout(n + 1);
int timer = 0;
function<void(int, int)> fill = [&](int v, int pr){
pw[v][0] = pr;
for (int i = 1; i <= lg; i++){
pw[v][i] = pw[pw[v][i - 1]][i - 1];
}
tin[v] = ++timer;
for (int i: g[v]){
if (i == pr) continue;
fill(i, v);
}
tout[v] = timer;
};
fill(1, 1);
auto check = [&](int x, int y){
return (tin[x] <= tin[y] && tout[x] >= tout[y]);
};
auto lca = [&](int x, int y){
if (check(x, y)) return x;
if (check(y, x)) return y;
for (int i = lg; i >= 0; i--){
if (!check(pw[x][i], y)){
x = pw[x][i];
}
}
return pw[x][0];
};
vector<arr3> t[n + 1];
int m; cin>>m;
while (m--){
int x, y, c; cin>>x>>y>>c;
t[lca(x, y)].pb({x, y, c});
}
FT T(n);
vector<ll> dp(n + 1);
function<void(int, int)> dfs = [&](int v, int pr){
ll S = 0;
for (int i: g[v]){
if (i == pr) continue;
dfs(i, v);
S += dp[i];
}
dp[v] = S;
for (auto [x, y, c]: t[v]){
dp[v] = max(dp[v], c + S + T.get(tin[x]) + T.get(tin[y]));
}
T.add(tin[v], tout[v], S - dp[v]);
};
dfs(1, 0);
cout<<dp[1]<<"\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... |