#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = (int)2e5 + 5;
typedef pair<ll,ll> point;
#define x first
#define y second
point operator +(const point &a, const point &b){ return {a.x + b.x, a.y + b.y}; }
point operator -(const point &a, const point &b){ return {a.x - b.x, a.y - b.y}; }
ll dot(const point &a, const point &b){ return a.x * b.x + a.y * b.y; }
ll cross(const point &a, const point &b){ return a.x * b.y - a.y * b.x; }
ll area2(const point &a, const point &b, const point &c){ return cross(b - a, c - a); }
struct hull : vector<point>{
void add_point(const point &p){ // p is greater than all the previous ones
while(size() > 1 and area2(at(size()-2), at(size()-1), p) >= 0)
pop_back();
push_back(p);
}
ll max_dot(const point &p){
int l = 0, r = (int)size() - 1;
while(l < r){
int mid = (l + r)>>1;
if(dot(at(mid), p) <= dot(at(mid + 1), p))
l = mid + 1;
else
r = mid;
}
return dot(at(l), p);
}
};
vector<pair<int,ll>> G[maxn];
ll speed[maxn], start[maxn], dp[maxn], sumW[maxn];
int n, sz[maxn];
void dfs(int u, int p){
sz[u] = 1;
for(auto [v, w]:G[u]){
if(v == p)
continue;
sumW[v] = sumW[u] + w;
dfs(v, u);
sz[u] += sz[v];
}
}
vector<hull> lights;
hull heavy;
void dfsHLD(int u, int p){
if(u != 1){
dp[u] = -1e18;
for(int i = 0; i < (int)lights.size(); i++)
dp[u] = max(dp[u], lights[i].max_dot({speed[u], 1}));
if(!heavy.empty())
dp[u] = max(dp[u], heavy.max_dot({speed[u], 1}));
dp[u] = sumW[u] * speed[u] + start[u] - dp[u];
}
heavy.add_point({sumW[u], -dp[u]});
lights.push_back(heavy);
int bigChild = -1;
for(auto [v, _]:G[u])
if(v != p and (bigChild == -1 or sz[bigChild] < sz[v]))
bigChild = v;
for(auto [v, w]:G[u])
if(v != bigChild and v != p){
heavy.clear();
dfsHLD(v, u);
}
heavy = lights.back();
lights.pop_back();
if(bigChild != -1)
dfsHLD(bigChild, u);
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
for(int i = 1; i < n; i++){
int u, v, w;
cin >> u >> v >> w;
G[u].push_back({v, w});
G[v].push_back({u, w});
}
for(int i = 2; i <= n; i++)
cin >> start[i] >> speed[i];
dfs(1,-1);
dfsHLD(1,-1);
for(int i = 2; i <= n; i++)
cout << dp[i] << ' ';
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
4940 KB |
Output is correct |
2 |
Correct |
6 ms |
5452 KB |
Output is correct |
3 |
Correct |
246 ms |
12460 KB |
Output is correct |
4 |
Execution timed out |
1098 ms |
15856 KB |
Time limit exceeded |
5 |
Correct |
125 ms |
19060 KB |
Output is correct |
6 |
Correct |
163 ms |
22412 KB |
Output is correct |
7 |
Correct |
76 ms |
13524 KB |
Output is correct |
8 |
Execution timed out |
1076 ms |
18204 KB |
Time limit exceeded |
9 |
Execution timed out |
1080 ms |
19240 KB |
Time limit exceeded |
10 |
Execution timed out |
1052 ms |
18772 KB |
Time limit exceeded |