zoukankan      html  css  js  c++  java
  • 克鲁斯卡尔

    最小生成树是将一个点阵联通所需要的最短的路径总长度。

    #include<iostream>
    #include<cmath>
    #include<cstdio>
    #include<cstdlib>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    inline int read()
    {
        int x=0,f=1;
        char ch;
        do
        {
            ch=getchar();
            if(ch=='-') f=-1;
        }while(ch<'0'||ch>'9');
        do
        {
            x=x*10+(ch-'0');
            ch=getchar();
        }while(ch>='0'&&ch<='0');
        return x*f;
    }
    struct node
    {
        int a,b,c;
    }s[10000];
    bool cmp(const node & x,const node & y){return x.c<y.c;}//根据路径的长度来排序 
    int f[10000];
    int getf(int v)//寻找他们的祖先 
    {
        if(f[v]==v) return v;//自己是自己的祖先 
        else
        {
            f[v]==getf(f[v]);//找自己祖先的祖先 
            return f[v];
        }
    }
    int main()
    {
        int n,m;
        n=read();
        m=read();
        int i,j,k;
        for(i=1;i<=n;i++) f[i]=i;
        for(i=1;i<=m;i++)
        {
            cin>>s[i].a>>s[i].b>>s[i].c;
        }
        sort(s+1,s+n+1,cmp);
        int ans=0;
        int cnt=0;
        for(i=1;i<=n;i++)
        {
            int h1,h2;
            h1=getf(s[i].a);
            h2=getf(s[i].b);
            if(h1!=h2)//如果不在一起,说明树还没有建好,就合并。 
            {
                ans+=s[i].c;//答案增加 
                cnt++;//路径数目增加 
                f[h2]=h1;//标记 
            }
            if(cnt==n-1) break;//N个点需要n-1条边 
        }
        cout<<ans;
        return 0;
    }

    祝大家编程顺利。

    蒟蒻总是更懂你✿✿ヽ(°▽°)ノ✿
  • 相关阅读:
    一个简单的空间配置器
    【转】c++中placement new操作符
    类的operator new与operator delete的重载【转】
    STL中常用的c++语法
    java编程思想-多态
    java编程思想-复用类(2)
    java编程思想-复用类
    import与require的区别
    gulp插件
    gulp-gulpfile.js语法说明
  • 原文地址:https://www.cnblogs.com/WWHHTT/p/7833985.html
Copyright © 2011-2022 走看看