-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdpOntree.cpp
More file actions
90 lines (74 loc) · 1.96 KB
/
dpOntree.cpp
File metadata and controls
90 lines (74 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define pb push_back
#define rep(i,a,b) for(int i=a;i<b;i++)
#define vl vector<ll>
#define vi vector<int>
#define lb lower_bound
#define ub upper_bound
#define all(x) (x).begin(), (x).end()
#define nline "\n"
// vector<vector<int>> vec( n , vector<int> (m, 0));
// priority_queue<pi, vector<pi>, greater<pi>>q;
typedef int64_t ll;
// Nice Question on DP on Tree
// Main idea is consider a tree with one root and other three all leafs and child of root
// then in this case you have to visit all weights twice except one where we end our journey
// so greedily we have to chose that leaf on which ending or journey will take overall leat cost
// so lets define dp[i] to be distance of furthermost leaf from ith node so so we will visit each leaf
// and comeback but in case for leaf where dp[1] is max we will vist it at last thus total anser will be
// ans=2*total weights-dp[1]
// if(there is only two node then dp[1]=total wights
// https://codeforces.com/problemset/problem/61/D
vector<ll>dp(200005, 0);
void dfs(int node, vector<pair<int, int>>adj[], int parent = 0)
{
dp[node] = 0;
for (auto it : adj[node])
{
int next = it.first;
int w = it.second;
if (next != parent)
{
dfs(next, adj, node);
dp[node] = max(dp[node], w + dp[next]);
}
}
}
void solve()
{
int n;
cin >> n;
vector<pair<int, int>>adj[n + 1];
ll ans = 0;
for (int i = 0; i < n - 1; i++)
{
int u, v, w;
cin >> u >> v >> w;
adj[u].pb({v, w});
adj[v].pb({u, w});
ans += w;
}
dfs(1, adj);
if (dp[1] == ans)
{
cout << ans << nline;
}
else
{
cout << 2 * ans - dp[1] << nline;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
solve();
return 0;
}