#include <bits/stdc++.h>
using namespace std;
struct LinearFn
{
int64_t m, t;
LinearFn() { m = t = 0; }
LinearFn(int64_t m_, int64_t t_) { m = m_, t = t_; }
int64_t operator()(int64_t x) { return m * x + t; }
};
bool intersects_earlier(LinearFn f, LinearFn g, LinearFn h)
{
return (double)(h.t - f.t) / (double)(f.m - h.m) <
(double)(g.t - f.t) / (double)(f.m - g.m);
}
#define N 100000
int64_t s[N], v[N], d[N], ans[N];
vector<pair<size_t, int64_t>> g[N];
LinearFn q[N];
size_t l;
void find_shortest_route(size_t u, size_t p)
{
bool removed_fn = 0;
LinearFn removed(0, 0);
size_t ol;
if (l)
{
size_t a = 0, b = l - 1;
while (a < b)
{
size_t mid = (a + b) / 2;
if (mid < l - 1 && q[mid](v[u]) <= q[mid + 1](v[u]))
b = mid;
else
a = mid + 1;
}
ans[u] = q[a](v[u]) + d[u] * v[u] + s[u];
LinearFn f(-d[u], ans[u]);
a = 0, b = l - 1;
while (a < b)
{
size_t mid = (a + b) / 2;
if (mid && intersects_earlier(q[mid - 1], q[mid], f))
b = mid;
else
a = mid + 1;
}
if (a == l - 1 && (!a || !intersects_earlier(q[a - 1], q[a], f)))
q[l++] = f;
else
{
removed_fn = 1;
removed = q[a];
q[a] = f;
ol = l;
l = a + 1;
}
}
else
l++;
for (auto [x, w] : g[u])
{
if (x != p)
{
d[x] = d[u] + w;
find_shortest_route(x, u);
}
}
if (removed_fn)
q[l - 1] = removed, l = ol;
else
l--;
}
int main()
{
size_t n;
cin >> n;
for (size_t i = 0; i + 1 < n; i++)
{
size_t u, v, w;
cin >> u >> v >> w;
g[u - 1].emplace_back(v - 1, w);
g[v - 1].emplace_back(u - 1, w);
}
for (size_t i = 1; i < n; i++)
cin >> s[i] >> v[i];
find_shortest_route(0, SIZE_MAX);
for (size_t i = 1; i < n; i++)
cout << ans[i] << ' ';
cout << '\n';
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
3 ms |
4180 KB |
Output isn't correct |
2 |
Correct |
7 ms |
4668 KB |
Output is correct |
3 |
Correct |
83 ms |
12356 KB |
Output is correct |
4 |
Correct |
104 ms |
16000 KB |
Output is correct |
5 |
Correct |
143 ms |
19464 KB |
Output is correct |
6 |
Correct |
166 ms |
23152 KB |
Output is correct |
7 |
Incorrect |
102 ms |
13316 KB |
Output isn't correct |
8 |
Incorrect |
178 ms |
17904 KB |
Output isn't correct |
9 |
Incorrect |
173 ms |
19520 KB |
Output isn't correct |
10 |
Incorrect |
157 ms |
18240 KB |
Output isn't correct |