标签:tps out algorithm int 联通 sign push col mic
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<vector> 5 using namespace std; 6 int f[100086]; 7 struct edge 8 { 9 int from; 10 int to; 11 int weight; 12 }; 13 int n, m; 14 int tot; 15 long long ans; 16 vector<edge>e; 17 int find(int x)//普通的并查集 18 { 19 if (f[x] == x) 20 return x; 21 else 22 return f[x] = find(f[x]); 23 } 24 void merge(int a, int b) 25 { 26 int x = find(a); 27 int y = find(b); 28 if (f[x] != f[y]) 29 f[y] = x; 30 } 31 bool cmp(edge a, edge b) 32 { 33 return a.weight < b.weight; 34 } 35 int main() 36 { 37 cin >> n >> m; 38 for (int i = 1; i <= n; i++) 39 f[i] = i;//并查集初始化 40 for (int i = 1; i <= m; i++) 41 { 42 int x, y, z; 43 cin >> x >> y >> z; 44 edge t; 45 t.from = x; 46 t.to = y; 47 t.weight = z; 48 e.push_back(t); 49 t.from = y; 50 t.to = x; 51 e.push_back(t); 52 } 53 sort(e.begin(), e.end(), cmp); 54 for (int i = 0; i < e.size(); i++) 55 { 56 if (find(e[i].from) != find(e[i].to)) 57 { 58 merge(e[i].from, e[i].to); 59 ans += e[i].weight; 60 } 61 } 62 cout << ans << endl; 63 return 0; 64 }
标签:tps out algorithm int 联通 sign push col mic
原文地址:https://www.cnblogs.com/HNFOX/p/11274539.html