#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pl;
typedef pair<int,int> pii;
typedef tuple<int,int,int> tpl;
#define all(a) a.begin(), a.end()
#define filter(a) a.erase(unique(all(a)), a.end())
struct line {
ll slope, c;
line() : slope(0), c(0) {}
line (ll u, ll v) : slope(u), c(v) {}
ll calc (ll x) { return slope * x + c; }
friend ld xSect (line a, line b) {
return (ld) (b.c - a.c) / (a.slope - b.slope);
}
friend bool valid (line a, line b, line c) {
return xSect(a, b) < xSect(b, c);
}
};
struct CHT {
vector<line> hull, save;
vector<int> used;
void push (line cur) {
int counter = 0;
while (hull.size() >= 2 && !valid(hull[hull.size() - 2], hull.back(), cur)) {
save.push_back(hull.back());
hull.pop_back(), counter++;
}
hull.push_back(cur), used.push_back(counter);
}
void rollback() {
hull.pop_back();
for (int i = 0; i < used.back(); i++) {
hull.push_back(save.back());
save.pop_back();
}
used.pop_back();
}
ll query (ll x) {
if (hull.empty()) return LLONG_MAX;
int ans = 0;
for (int mask = 1 << 18; mask; mask >>= 1) {
int tmp = mask | ans;
if (tmp < hull.size() && xSect(hull[tmp - 1], hull[tmp]) < x) ans |= mask;
}
return hull[ans].calc(x);
}
} hull;
const int mn = 1e5 + 5;
ll dist[mn], dp[mn], speed[mn], warmUp[mn];
vector<pl> adj[mn];
void dfs (int u, int p, ll wp) {
if (u != p) {
dist[u] = dist[p] + wp;
dp[u] = hull.query(speed[u]) + warmUp[u] + speed[u] * dist[u];
}
hull.push(line(-dist[u], dp[u]));
for (pl item : adj[u]) {
int v; ll w; tie(v, w) = item;
if (v != p) dfs(v, u, w);
}
hull.rollback();
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
for (int i = 1; i < n; i++) {
int a, b; ll c; cin >> a >> b >> c;
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
for (int i = 2; i <= n; i++) cin >> warmUp[i] >> speed[i];
dfs(1, 1, 0);
for (int i = 2; i <= n; i++) cout << dp[i] << " ";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |