This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 7;
const int INF = 1e9 + 7;
struct Edge{
int v, c;
Edge(int _v, int _c){
v = _v;
c = _c;
}
};
int n, down[N][2], up[N][2];
vector<Edge> adj[N];
void Dfs(int u, int p){
down[u][0] = 0;
down[u][1] = -INF;
for(Edge e : adj[u]){
int v = e.v;
int c = e.c;
if (v == p)
continue;
Dfs(v, u);
down[u][1] = max(down[u][1] + max(down[v][0], down[v][1] + c), down[u][0] + down[v][0] + c);
down[u][0] += max(down[v][0], down[v][1] + c);
}
}
void Dfs2(int u, int p){
if (p == -1){
up[u][0] = 0;
up[u][1] = -INF;
}
int sum = up[u][0];
multiset<int> s;
s.insert(up[u][1] - up[u][0]);
for(Edge e : adj[u]){
int v = e.v;
int c = e.c;
if (v == p)
continue;
sum += max(down[v][0], down[v][1] + c);
s.insert(down[v][0] + c - max(down[v][0], down[v][1] + c));
}
for(Edge e : adj[u]){
int v = e.v;
int c = e.c;
if (v == p)
continue;
sum -= max(down[v][0], down[v][1] + c);
s.erase(s.find(down[v][0] + c - max(down[v][0], down[v][1] + c)));
up[v][0] = sum + max(0, *(--s.end()) + c);
up[v][1] = sum + c;
s.insert(down[v][0] + c - max(down[v][0], down[v][1] + c));
sum += max(down[v][0], down[v][1] + c);
}
for(Edge e : adj[u]){
int v = e.v;
if (v == p)
continue;
Dfs2(v, u);
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for(int i = 1; i < n; i++){
int u, v, c;
cin >> u >> v >> c;
adj[u].push_back(Edge(v, c));
adj[v].push_back(Edge(u, c));
}
Dfs(1, -1);
Dfs2(1, -1);
int res = 0;
for(int i = 1; i <= n; i++)
res = max(res, up[i][0] + down[i][0]);
cout << res;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |