题目描述
如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出 orz
。
输入格式
第一行包含两个整数 N,M,表示该图共有 N 个结点和 M 条无向边。
接下来 M 行每行包含三个整数 Xi,Yi,Zi,表示有一条长度为 Zi 的无向边连接结点 Xi,Yi。
输出格式
如果该图连通,则输出一个整数表示最小生成树的各边的长度之和。如果该图不连通则输出 orz
。
输入输出样例
输入 #1
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3
输出 #1
7
说明/提示
数据规模:
对于 20% 的数据,N≤5,M≤20。
对于 40% 的数据,N≤50,M≤2500。
对于 70% 的数据,N≤500,M≤10^4。
对于 100\%100% 的数据:1≤N≤5000,1≤M≤2×10^5,1≤Zi≤10^4。
AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
int from;
int to;
int data;
}tree[200005];
int vis[200005];
int father(int x){
if(x==vis[x]){
return x;
}
return vis[x]=father(vis[x]);
}
void link(int x,int y){
int hx=father(x);
int hy=father(y);
vis[hx]=hy;
}
bool cmp(node a,node b){
return a.data<b.data;
}
int main(){
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
vis[i]=i;
}
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
tree[i].from=a;
tree[i].to=b;
tree[i].data=c;
}
sort(tree,tree+m,cmp);
int num=0;
int sum=0;
for(int i=0;i<m;i++){
//cout<<tree[i].from<<endl;
//cout<<father(tree[i].from)<<' '<<father(tree[i].to)<<endl;
if(father(tree[i].from)!=father(tree[i].to)){
link(tree[i].from,tree[i].to);
num+=tree[i].data;
sum++;
if(sum==n-1) break;
}
//cout<<num<<endl;
}
if(sum!=n-1){
printf("orz\n");
return 0;
}
printf("%d\n",num);
return 0;
}
//576