346. 走廊泼水节

思路

看代码就能理解该题思路,核心思想就是按照边权顺序生成完全图,新增的边权设置决定唯一性,证明略。

AC code

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
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 6010;
int n;
struct Edge{
int a, b, w;
bool operator < (const Edge& e) const {
return w < e.w;
}
}e[N];
int p[N], s[N];

int find(int x){
return p[x] == x ? p[x] : p[x] = find(p[x]);
}

int main(){
int T;
cin >> T;
while(T--){
cin >> n;
for(int i = 0; i < n - 1; i++){
int a, b, w;
cin >> a >> b >> w;
e[i] = {a, b, w};
}
sort(e, e + n - 1);
for(int i = 1; i <= n; i++) p[i] = i, s[i] = 1;

int res = 0;
for(int i = 0; i < n - 1; i++){
int a = find(e[i].a), b = find(e[i].b), w = e[i].w;
if(a != b){
res += (s[a] * s[b] - 1) * (w + 1);
s[b] += s[a];
p[a] = b;
}
}
cout << res << endl;
}
return 0;
}