题目描述
如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出orz
分析
复习ing
就是一个最小生成树的模板题Kruskal
写了并查集优化。
code
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
struct arr{
int x,y,w,next;
}edge[300000];
int ls[200000];
int n,m;
int edge_m;
bool cmp(arr a,arr b)//排序。
{
return a.w<b.w;
}
int f[200000];//并查集数组。
int find(int x)//并查集查找。
{
if (f[x]==x) return x;
else{
f[x]=find(f[x]);
return f[x];
}
}
void merge(int x,int y)//并查集合并。
{
int x1,y1;
x1=find(x);
y1=find(y);
f[x1]=y1;
}
void add(int x,int y,int w)//加边
{
edge_m++;
edge[edge_m]=(arr){x,y,w};
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
add(x,y,w);
}
sort(edge+1,edge+m+1,cmp);
for (int i=1;i<=n;i++) f[i]=i;
int ans=0;
int num=0;
int i=1;
while ((num<n-1)&&(i<=m))//Kruskal的本体
{
if (find(edge[i].x)!=find(edge[i].y))
{
merge(edge[i].x,edge[i].y);
ans+=edge[i].w;
num++;
}
i++;
}
if (i<=m) printf("%d",ans);
else printf("orz");
}