比较显然,从根节点出发,并不方便做题,所以要颠倒关系,然后就有了树型dp。
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
using namespace std;
const int N = 1e6+5;
struct edge{
int t, w;
};
vector<edge> g[N];
int tot;
int dfs(int i, int fa)
{
int mmax = 0;
for(edge &e : g[i])
{
if(e.t == fa) continue;
e.w += dfs(e.t, i);
mmax = max(mmax, e.w);
}
for(edge &e : g[i])
{
if(e.t == fa) continue;
tot += mmax - e.w;
}
return mmax;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int s;
cin >> s;
for(int i = 1; i <= n - 1; ++i)
{
int a, b, w;
cin >> a >> b >> w;
g[a].push_back(edge{b, w});
g[b].push_back(edge{a, w});
}
int ans = dfs(s, 0);
cout << tot << endl;
}