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 int;
const int Mxn = 1e5 + 1;
const int mxn = 2e5 + 1;
//hld
//nomás porq soy un mamador y es menos código hacer lca así que con binary lifting
int tin[Mxn], tout[Mxn], Sz[Mxn], head[Mxn], P[Mxn], Depth[Mxn], cnt = 1;
vector<int> g[Mxn];
void get_sz(int node = 1, int parent = 1) {
Sz[node] = 0; Depth[node] = Depth[parent] + 1; P[node] = parent;
if (g[node][0] == parent) swap(g[node][0], g[node].back());
for (auto & child : g[node]) {
if (child == parent) continue;
get_sz(child, node); Sz[node] += Sz[child];
if (Sz[child] > Sz[g[node][0]]) swap(child, g[node][0]);
}
}
void dfs_hld(int node = 1, int parent = 1) {
tin[node] = cnt++;
for (auto child : g[node]) {
if (child == parent) continue;
head[child] = (child == g[node][0]) ? head[node] : child;
dfs_hld(child, node);
}
tout[node] = cnt++;
}
void init_hld() {head[1] = 1; Depth[1] = 0; get_sz(), dfs_hld();}
int LCA(int A, int B) {
for (; head[A] != head[B]; A = P[head[A]]) {
if (Depth[head[A]] < Depth[head[B]]) swap(A, B);
}
return (Depth[A] < Depth[B]) ? A : B;
}
//fenwi
struct fenwi {
ll BIT[mxn];
void upd(int i, ll val = 0) {
for (; i < mxn; i += i&-i) BIT[i] += val;
}
ll sum(int i, ll val = 0) {
for (; i > 0; i -= i&-i) val += BIT[i];
return val;
}
ll query(int a, int b) {
return sum(tin[a]) + sum(tin[b]) - 2*sum(tin[LCA(a, b)]);
}
} bit[2];
//solve
struct query {int a, b, c;};
ll dp[Mxn], children_sum[Mxn];
vector<query> Q[Mxn];
void dfs(int node = 1, int parent = 1) {
children_sum[node] = 0;
for (auto child : g[node]) {
if (child == parent) continue;
dfs(child, node);
children_sum[node] += dp[child];
}
dp[node] = children_sum[node];
bit[0].upd(tin[node], children_sum[node]);
bit[0].upd(tout[node], -children_sum[node]);
for (auto [a, b, c] : Q[node]) {
dp[node] = max(dp[node], bit[0].query(a, b) + children_sum[node] - bit[1].query(a, b) + c);
}
bit[1].upd(tin[node], dp[node]);
bit[1].upd(tout[node],-dp[node]);
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int n, m; cin >> n;
for (int i = 1; i < n; i++) {
int x, y; cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
cin >> m; init_hld();
for (int i = 0; i < m; i++) {
int x, y, c; cin >> x >> y >> c;
Q[LCA(x, y)].push_back({x, y, c});
}
dfs();
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... |