AcWing 1143. 联络员
原题链接
简单
作者:
Value
,
2020-10-13 10:49:12
,
所有人可见
,
阅读 361
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10000;
int n, m;
struct node{
int x, y, w;
}ege[N];
int parent[N];
int res = 0, k = 0;
int find(int x){
if(parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
void read(){
cin >> n >> m;
for(int i = 0; i <= n; i ++ ) parent[i] = i;
for(int i = 0; i < m; i ++ ){
int p, u, v, w; cin >> p >> u >> v >> w;
if(p == 1){
int pu = find(u), pv = find(v);
if(pu != pv) parent[pu] = pv;
res += w;
}else{
ege[k] = {u, v, w};
k ++ ;
}
}
}
bool cmp(node a, node b){
return a.w < b.w;
}
void kruskal(){
sort(ege, ege + k, cmp);
for(int i = 0; i < k; i ++ ){
int px = find(ege[i].x), py = find(ege[i].y);
if(px != py){
res += ege[i].w;
parent[px] = py;
}
}
}
int main(){
read();
kruskal();
cout << res << endl;
return 0;
}