#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;
stack<pair<int,line>> save;
stack<int> top;
void push (line cur) {
if (hull.size() < 2) {
top.push(hull.size()), save.emplace(hull.size(), cur);
hull.push_back(cur);
}
else {
int pos = 0;
for (int mask = 1 << 18; mask; mask >>= 1) {
int tmp = pos | mask;
if (tmp <= top.top() && valid(hull[tmp - 1], hull[tmp], cur)) pos |= mask;
}
if (pos + 1 == hull.size()) hull.push_back(cur);
top.push(pos + 1), save.emplace(pos + 1, hull[pos + 1]);
hull[pos + 1] = cur;
}
}
void rollback() {
int p; line cur; tie(p, cur) = save.top();
hull[p] = cur, top.pop(), save.pop();
}
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 <= top.top() && 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... |