Kruskal

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
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,fa[5001];
int tmp1,tmp2,tmp3;
int sum=0,ans=0;
struct node
{
int x,y,v;
}edge[200001];
int find(int x)
{
if(x==fa[x])return x;
else return fa[x]=find(fa[x]);
}
bool comp(const node &x,const node &y)
{
return x.v<y.v;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].v);
for(int i=1;i<=n;++i)fa[i]=i;
sort(edge+1,edge+1+m,comp);
for(int i=1;i<=m;++i)
{
tmp1=find(edge[i].x);
tmp2=find(edge[i].y);
if(tmp1==tmp2)continue;
ans+=edge[i].v;
sum++;
fa[tmp1]=tmp2;
}
if(sum==n-1)cout<<ans;
else cout<<"orz";
return 0;
}
显示 Gitment 评论