-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathP1131.cc
45 lines (39 loc) · 1.01 KB
/
P1131.cc
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
#include <cstdio>
#include <cstdlib>
#include <vector>
using std::vector;
#define maxn 500000
typedef long long ll;
struct AdjNode {
int v;
int weight;
AdjNode(int v, int weight) : v(v), weight(weight) {}
};
vector<AdjNode> tree[maxn];
ll len[maxn];
ll Dfs(int v, int parent) {
ll numq = 0;
for (auto it = tree[v].begin(); it != tree[v].end(); it++)
if (it->v != parent) {
numq += Dfs(it->v, v);
if (len[it->v] + it->weight > len[v]) len[v] = len[it->v] + it->weight;
}
for (auto it = tree[v].begin(); it != tree[v].end(); it++)
if (it->v != parent) {
numq += len[v] - len[it->v] - it->weight;
}
return numq;
}
int main() {
int n, s, a, b, t;
scanf("%d %d", &n, &s);
s--;
for (int i = 0; i < n - 1; i++) {
scanf("%d %d %d", &a, &b, &t);
a--; b--;
tree[a].push_back(AdjNode(b, t));
tree[b].push_back(AdjNode(a, t));
}
printf("%lld\n", Dfs(s, -1));
exit(0);
}