#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template<typename T> using ordered_set = tree<T,null_type,less_equal<T>,rb_tree_tag,
tree_order_statistics_node_update>;
#define ll long long
#define pi pair<int,int>
#define vi vector<int>
#define pb push_back
#define all(a) a.begin(),a.end()
const int mxn = 1e5+1;
vector<pi> g[mxn];
ll dp[mxn], res[mxn];
void pre_dfs(int u, int p){
for(auto [v,c] : g[u]) if(v!=p){
pre_dfs(v,u);
dp[u] = max(dp[u],dp[v]+c);
}
}
void dfs(int u, int p){
ll m1 = 0, m2 = 0;
int ind = 0;
dp[u] = 0;
for(auto [v,c] : g[u]){
dp[u] = max(dp[u],dp[v]+c);
if(dp[v]+c > m1) m2 = m1, m1 = dp[v]+c, ind = v;
else if(dp[v]+c > m2) m2 = dp[v]+c;
}
res[u] = dp[u];
for(auto [v,c] : g[u]) if(v!=p){
if(v==ind) dp[u] = m2;
else dp[u] = m1;
dfs(v,u);
}
}
void solve(){
int n,k; cin >> n >> k;
for(int i = 1; i < n; i++){
int u,v,c; cin >> u >> v >> c;
g[u].pb({v,c}); g[v].pb({u,c});
}
pre_dfs(1,1);
dfs(1,1);
for(int i = 1; i <= n; i++)
cout << res[i] << '\n';
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
int t = 1;
// cin >> t;
while(t--){solve();}
}
| # | 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... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |