就这个Kruskal爽!!!
2024-08-23 08:43:16
发布于:广东
19阅读
0回复
0点赞
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct node2{
int x, y, len;
bool operator < (const node2 &b) const{
return len < b.len;
}
}edges[200005];
int father[5005];
int n, m, x, y, z;
int find(int idx){
if(idx != father[idx]) idx = find(father[idx]);
return father[idx];
}
bool merge(int x, int y){
int p = find(x), q = find(y);
if(p == q) return 0;
father[max(p, q)] = min(p, q);
return 1;
}
int kruskal(){
sort(edges + 1, edges + m + 1);
int ct = 0, ctt = 0;
for(int i = 1; i <= n; i++) father[i] = i;
for(int i = 1; i <= m; i++){
if(merge(edges[i].x, edges[i].y)){
ct += edges[i].len, ctt++;
if(ctt >= n - 1) return ct;
}
}
return -1;
}
int read(){
char c = getchar();
int x = 0, f = 1;
while(!isdigit(c)){
if(c == '-') f = -f;
c = getchar();
}
while(isdigit(c)){
x = (x << 3) + (x << 1) + c - '0';
c = getchar();
}
return x * f;
}
int main(){
n = read(), m = read();
for(int i = 1; i <= m; i++){
x = read(), y = read(), z = read();
edges[i] = {x, y, z};
}
int ans = kruskal();
if(ans == -1) cout << "orz";
else cout << ans;
return 0;
}
这里空空如也
有帮助,赞一个