#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ii pair < int , int >
#define il pair < int , ll >
#define fi first
#define se second
constexpr int Nmax = 1e5 + 5;
ll f[Nmax], v[Nmax], d[Nmax], s[Nmax];
vector < il > adj[Nmax];
struct line {
ll a, b;
ll calc(ll x) {
return a * x + b;
}
double intersect(line x) {
return (double)(x.b - b) / (double)(a - x.a);
}
}a[Nmax];
struct ope {
int id, old_top;
line old_id;
};
stack < ope > st;
int top = 0;
void add(line x) {
int l = 2, r = top, ans = top + 1;
while (l <= r) {
int mid = (l + r) / 2;
if (a[mid - 1].intersect(x) <= a[mid - 1].intersect(a[mid])) {
ans = mid;
r = mid - 1;
}
else l = mid + 1;
}
st.push({ans, top, a[ans]});
top = ans;
a[ans] = x;
}
void undo() {
auto t = st.top();
st.pop();
top = t.old_top;
a[t.id] = t.old_id;
}
ll query(ll x) {
int l = 2, r = top, ans = 1;
while (l <= r) {
int mid = (l + r) / 2;
if (a[mid - 1].intersect(a[mid]) <= x) {
ans = mid;
l = mid + 1;
}
else r = mid - 1;
}
return a[ans].calc(x);
}
void dfs(int i, int j) {
if (i != 1) {
f[i] = query(v[i]) + s[i] + v[i] * d[i];
}
add(line{-d[i], f[i]});
for (auto x:adj[i]) {
int u = x.fi, w= x.se;
if (u == j) continue;
d[u] = d[i] + w;
dfs(u, i);
}
undo();
}
signed main() {
if (fopen(".inp","r")) {
freopen(".inp","r",stdin);
freopen(".out","w",stdout);
}
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int u, v;
ll w;
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
for (int i = 2; i <= n; i++) {
cin >> s[i] >> v[i];
}
dfs(1, 0);
for (int i = 2; i <= n; i++) {
cout << f[i] << " ";
}
return 0;
}
Compilation message
harbingers.cpp: In function 'int main()':
harbingers.cpp:82:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
82 | freopen(".inp","r",stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~
harbingers.cpp:83:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
83 | freopen(".out","w",stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
6488 KB |
Output is correct |
2 |
Correct |
2 ms |
7000 KB |
Output is correct |
3 |
Correct |
34 ms |
13136 KB |
Output is correct |
4 |
Correct |
40 ms |
16208 KB |
Output is correct |
5 |
Correct |
52 ms |
18888 KB |
Output is correct |
6 |
Correct |
67 ms |
21924 KB |
Output is correct |
7 |
Correct |
40 ms |
13308 KB |
Output is correct |
8 |
Correct |
80 ms |
17344 KB |
Output is correct |
9 |
Correct |
72 ms |
18884 KB |
Output is correct |
10 |
Correct |
67 ms |
17652 KB |
Output is correct |