zoukankan      html  css  js  c++  java
  • kruskal 处理最短路 问题 A: 还是畅通工程

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<vector>
    #include<map>
    #include<cmath>
    #include<cstdio>
    #include<queue>
    typedef long long ll;
    const int mod = 1e9+7;
    const int maxn = 1000000;
    const int inf = 0x3f3f3f3f;
    int m;
    using namespace std;
    int pre[maxn]; 
    struct node 
    {
        int x;
        int y;
        int z;
    }pos[maxn];
    
    int cmp(node x,node y)
    {
        if(x.z < y.z)
            return 1;
        return 0;
    }
    
    void init()//初始化 
    {
        for(int i=0;i<=m;i++)
        {
            pre[i]=i;
        }
    }
    
    int Find(int x) //找掌门函数 
    {
        while(x!=pre[x])
        x=pre[x];
        return x;
    }
    
    void uoin(int x,int y)//打架函数 
    {
        int fx=Find(x);
        int fy=Find(y);
        if(fx!=fy)
        {
            pre[fx]=fy;
        }
    }
    int main()
    {
         ios::sync_with_stdio(false);
        cin.tie(0);cout.tie(0);
        
        while(scanf("%d",&m),m)
        {
            
            int i;
            
            int n = m * (m-1) / 2;
            
            for(int i =1;i<=m;i++)
            {
                pre[i]=i;
            }
            
            for(i=1;i<=n;i++)
            {
                cin>>pos[i].x>>pos[i].y>>pos[i].z;
            }
            
            sort(pos+1,pos+1+n,cmp);//排序加边 找最小 
            
        
            int minm = 0;
            int cnt=0; 
            for(i=1;i<=n;i++)
            {
                if(Find(pos[i].x)!=Find(pos[i].y))//掌门不同 
                {
                    uoin(pos[i].x,pos[i].y);//打一架 
                    minm+=pos[i].z;//加权 
                    
                    cnt++;//有几个点在树里面 
                    
                    if(cnt == m-1)
                    {
                        break;
                    }    
                }
            }
            cout<<minm<<endl; 
        }
        return 0;
    }

    关于找掌门函数和打架函数的意思(并查集)

    https://blog.csdn.net/qq_41593380/article/details/81146850

  • 相关阅读:
    测试流程之需求评审
    如何编写测试计划
    一定要知道的,那些Linux操作命令
    线上bug分析
    做一个靠谱的软件测试人员
    测试方向
    怎样才能提交一个让开发人员拍手叫好的bug单
    软件测试职业发展
    MongoDB的启动流程
    百度语音
  • 原文地址:https://www.cnblogs.com/lightWh1te/p/13386614.html
Copyright © 2011-2022 走看看