This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/**
* author: wxhtzdy
* created: 08.08.2022 18:12:39
**/
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class fenwick {
public:
vector<T> fenw;
int n;
fenwick(int _n) : n(_n) {
fenw.resize(n);
}
void modify(int x, T v) {
while (x < n) {
fenw[x] += v;
x |= (x + 1);
}
}
T get(int x) {
T v{};
while (x >= 0) {
v += fenw[x];
x = (x & (x + 1)) - 1;
}
return v;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<vector<tuple<int, int, int>>> g(n);
for (int i = 0; i < n - 1; i++) {
int u, v, w0, w1;
cin >> u >> v >> w0 >> w1;
--u; --v;
g[u].emplace_back(v, w0, w1);
g[v].emplace_back(u, w0, w1);
}
vector<vector<int>> up(n, vector<int>(2));
vector<int> dep(n);
vector<int> par(n);
vector<int> tin(n);
vector<int> tout(n);
int T = 0;
function<void(int, int)> Dfs = [&](int v, int pr) {
tin[v] = ++T;
par[v] = pr;
dep[v] = dep[pr] + 1;
for (auto& p : g[v]) {
int u = get<0>(p);
if (u != pr) {
Dfs(u, v);
up[u][0] = get<1>(p);
up[u][1] = get<2>(p);
}
}
tout[v] = T;
};
Dfs(0, 0);
const int L = 25;
vector<vector<int>> jump(n, vector<int>(L));
for (int i = 0; i < n; i++) {
jump[i][0] = par[i];
}
for (int j = 1; j < L; j++) {
for (int i = 0; i < n; i++) {
jump[i][j] = jump[jump[i][j - 1]][j - 1];
}
}
auto LCA = [&](int u, int v) {
if (dep[u] > dep[v]) {
swap(u, v);
}
for (int i = L - 1; i >= 0; i--) {
if (dep[jump[v][i]] >= dep[u]) {
v = jump[v][i];
}
}
for (int i = L - 1; i >= 0; i--) {
if (jump[u][i] != jump[v][i]) {
u = jump[u][i];
v = jump[v][i];
}
}
return u == v ? u : jump[u][0];
};
fenwick<int> fenw(n + 1);
auto Add = [&](int x, int y) {
fenw.modify(tin[x], +1);
fenw.modify(tin[y], -1);
};
for (int i = 0; i < n - 1; i++) {
int L = LCA(i, i + 1);
Add(i, L);
Add(i + 1, L);
}
long long ans = 0;
for (int i = 1; i < n; i++) {
ans += min(up[i][0] * 1LL * (fenw.get(tout[i]) - fenw.get(tin[i] - 1)), (long long) up[i][1]);
}
cout << ans << '\n';
return 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... |