#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Line {
mutable ll k, m, p;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(ll x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
static const ll inf = LLONG_MAX;
ll divFloor(ll a, ll b) {
return a / b - ((a ^ b) < 0 && a % b);
}
bool isect(iterator x, iterator y) {
if (y == end()) { x->p = inf; return false; }
if (x->k == y->k) x->p = (x->m > y->m ? inf : -inf);
else x->p = divFloor(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
// add line: y = kx + m, return rollback info
// trả về iterator nếu line này còn tồn tại, ngược lại trả về end()
pair<iterator, vector<Line>> add(ll k, ll m) {
auto z = insert({k,m,0}), y = z++, x = y;
vector<Line> erased;
while (isect(y,z)) {
erased.push_back(*z);
z = erase(z);
}
if (x != begin() && isect(--x,y)) {
erased.push_back(*y);
erase(y);
}
while ((y = x) != begin() && (--x)->p >= y->p) {
erased.push_back(*y);
erase(y);
}
return {y, erased};
}
ll query(ll x) {
assert(!empty());
auto l = *lower_bound(x);
return l.k * x + l.m;
}
};
int N;
vector<vector<pair<int,ll>>> adj;
vector<ll> S, V, dist, opt;
LineContainer cht;
void dfs(int u, int p) {
if (u == 1) {
opt[u] = 0;
} else {
ll best = cht.query(V[u]);
opt[u] = S[u] + V[u] * dist[u] + best;
}
// thêm line của u
auto [it, erased] = cht.add(-dist[u], opt[u]);
for (auto [v,w] : adj[u]) if (v != p) {
dist[v] = dist[u] + w;
dfs(v,u);
}
// rollback
if (it != cht.end()) cht.erase(it);
for (auto &ln : erased) cht.insert(ln);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N;
adj.assign(N+1, {});
for (int i=0;i<N-1;i++) {
int u,v; ll w; cin >> u >> v >> w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
}
S.assign(N+1,0);
V.assign(N+1,0);
dist.assign(N+1,0);
opt.assign(N+1,0);
for (int i=2;i<=N;i++) cin >> S[i] >> V[i];
dfs(1,0);
for (int i=2;i<=N;i++) cout << opt[i] << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |