This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Success consists of going from failure to failure without loss of enthusiasm
#include <bits/stdc++.h>
using namespace std;
#define nl '\n'
#define pb push_back
#define f first
#define s second
#define mp make_pair
using ll = long long;
template<class T> using V = vector<T>;
using pi = pair<int,int>;
using vi = V<int>;
using vpi = V<pi>;
const int MOD = 1e9 + 7;
const int LG = 19;
int main() {
cin.tie(0)->sync_with_stdio(0);
int N; cin >> N;
vi W(N - 1), MW(N - 1);
V<vpi> adj(N); for(int i = 0; i < N - 1; i++) {
int u, v; cin >> u >> v; --u, --v;
cin >> W[i] >> MW[i];
adj[u].pb(mp(v, i));
adj[v].pb(mp(u, i));
}
V<vi> up(N, vi(LG)); vi idx(N, -1), dep(N, 0);
function<void(int, int)> gen = [&](int u, int p) {
up[u][0] = p;
for(int i = 1; i < LG; i++) up[u][i] = up[up[u][i-1]][i-1];
for(auto& e : adj[u]) {
int v, i; tie(v, i) = e;
if (v == p) continue;
idx[v] = i; dep[v] = dep[u] + 1;
gen(v, u);
}
};
gen(0, 0);
auto jmp = [&](int u, int d) {
for(int i = 0; i < LG; i++) if ((d >> i) & 1) u = up[u][i];
return u;
};
auto lca = [&](int a, int b) {
if (dep[a] < dep[b]) swap(a, b);
a = jmp(a, dep[a] - dep[b]);
if (a == b) return a;
for(int i = LG - 1; i >= 0; i--) {
if (up[a][i] != up[b][i]) {
a = up[a][i], b = up[b][i];
}
}
return up[a][0];
};
vi BAL(N);
for(int i = 0; i + 1 < N; i++) {
// path from i to i + 1
int l = lca(i, i + 1);
// cerr << i << " " << i + 1 << " ==> " << l << endl;
BAL[i]++, BAL[i + 1]++;
BAL[l] -= 2;
}
ll ans = 0;
function<int(int, int)> dfs = [&](int u, int p) {
int bal = 0;
for(auto& e : adj[u]) {
int v, i; tie(v, i) = e;
if (v == p) continue;
bal += dfs(v, u);
}
bal += BAL[u];
// cerr << u << " => " << bal << endl;
if (idx[u] != -1) {
int i = idx[u];
ans += min(W[i] * 1LL * bal, MW[i] + 0LL);
}
return bal;
};
dfs(0, -1);
cout << ans << nl;
exit(0-0);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |