zoukankan      html  css  js  c++  java
  • 51nod 1212 无向图最小生成树(Kruskal模版题)

    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 <algorithm>
    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    struct node
    {
        int x,y,z;
    }edge[50001];
    int tot,fa[1001],i,j,n,m;
    int find_fa(int x)
    {
        if(fa[x]==x)
        return x;
        else return find_fa(fa[x]);
    }
    bool cmp(node a,node b)
    {
        return a.z<b.z;
    }
    int main()
    {
        ios::sync_with_stdio(false); 
        cin>>n>>m;
        int s,e,w;
        for(i=0;i<m;++i)
        {
            cin>>s>>e>>w;
            tot++;
            edge[tot].x=s;
            edge[tot].y=e;
            edge[tot].z=w;
        }
        for(i=1;i<=n;++i) fa[i]=i;
        sort(edge+1,edge+1+tot,cmp);
        int ans=0,h=0;
        for(i=1;i<=tot;++i)
        {
            int x=find_fa(edge[i].x),y=find_fa(edge[i].y);
            if(x!=y)
            {
                h++;
                fa[y]=x;
                ans+=edge[i].z;
                if(h==n-1)
                break;
            }
        }
        cout<<ans;
    }
    
    
    我们都在命运之湖上荡舟划桨,波浪起伏着而我们无法逃脱孤航。但是假使我们迷失了方向,波浪将指引我们穿越另一天的曙光。
  • 相关阅读:
    Git log、diff、config 进阶
    Firefox 修改User Agent
    改Chrome的User Agent,移动版网络
    ThinkPHP 更新数据 save方法
    ThinkPHP:create()方法有什么用呢?
    js控制select选中显示不同表单内容
    GPS通讯协议协议(NMEA0183)
    Linux pkg-config命令
    OpenCV编程
    GTK编程
  • 原文地址:https://www.cnblogs.com/ruojisun/p/6394128.html
Copyright © 2011-2022 走看看