1212 无向图最小生成树
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
Output示例
37
#include<iostream>
#include<algorithm>
using namespace std;
struct node {
int x,y,len;}B[50005];
int fa[2005];
int findfa(int x)
{
if (fa[x]==x) return x;
else return fa[x]=findfa(fa[x]);
}
bool cmp(struct node a,struct node b)
{
return a.len<b.len;
}
int main()
{
int n,m,sum_len=0;
cin>>n>>m;
for (int i=0;i<m;i++)
cin>>B[i].x>>B[i].y>>B[i].len;
sort(B,B+m,cmp);
for (int i=0;i<=n;i++)
{
fa[i]=i;
}
for (int i=0,j=0;i<m&&j<n;i++)
{
int fx=findfa(B[i].x);
int fy=findfa(B[i].y);
if (fx!=fy)
{
sum_len+=B[i].len;
fa[fx]=fy;
}
}
cout<<sum_len;
return 0;
}