51nod 1212 无向图最小生成树

来源:互联网 发布:北京行知实验小学咋样 编辑:程序博客网 时间:2024/06/05 02:17

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 141 2 42 3 83 4 74 5 95 6 106 7 27 8 18 9 72 8 113 9 27 9 63 6 44 6 141 8 8
Output示例
37

解题思路:这题就是套模板,利用并查集找最小生成树。。。

代码如下:

#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;struct P{    int x,y,z;}a[50050];int f[1001];int find(int x)///并查集{    return f[x] == x ? x : f[x] = find(f[x]);}bool cmp(P a,P b){    return a.z<b.z;}int merge(P a){    int x = find(a.x);    int y = find(a.y);    if(x!=y){f[x] = y; return 1;}    return 0;}int main(){    int n,m;    scanf("%d %d",&n,&m);    for(int i=0;i<=n;i++)        f[i] = i;    for(int i=0;i<m;i++)        scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].z);    sort(a,a+m,cmp);    int sum=0;    for(int i=0;i<m;i++)        if(merge(a[i]))            sum+=a[i].z;    printf("%d\n",sum);    return 0;}