zoukankan      html  css  js  c++  java
  • 【模板】最小生成树——Kruskal算法

    【模板】最小生成树——Kruskal算法

    Kruskal算法(n*n+m)

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<string>
    #include<queue>
    #include<stack>
    #include<algorithm>
    #include<vector>
    #include<map>
    using namespace std;
    const int INF= 0x3f3f3f3f;
    struct MS
    {
        int u, v, w;
    }gr[500001];
    int fa[500100];
    int n, m;
    bool cmp(MS X,MS Y)
    {
        return X.w < Y.w;//结构体重载
    }
    int findx(int x)//并查集
    {
        if(x!=fa[x])
            fa[x] = findx(fa[x]);
        return fa[x];
    }
    void unity(int x,int y)//祖先合并
    {
        int x1 = findx(x);
        int y1 = findx(y);
        if(x1!=y1)
            fa[x1] = y1;
    }
    void make_out()//初始化并查集
    {
        for (int i = 1; i<= n;i++)
           { fa[i] = i;
           }
    }
    int main()
    {
        cin >> n >> m;
        int total = 0;
        for (int i = 1; i<= m;i++)
        {
            cin >> gr[i].u >> gr[i].v >> gr[i].w;
        }
        make_out();
        sort(gr + 1, gr + m + 1, cmp);//根据权值从小到大排序
        for (int i = 1; i<= m;i++)
        {
            int u1 = gr[i].u;
            int v1 = gr[i].v;
            if(findx(u1)!=findx(v1))
            {
                total += gr[i].w;
                unity(u1, v1);
            }
        }
        int ans = 0;
        for (int i = 1; i <= n;i++)
        {
            if(fa[i]!=i)//判断是不是联通图
                ans++;
        }
        if(ans==n-1)
            cout << total;
            else{
                cout << "orz";
            }
        return 0;
    }
    
    
    
    
    
    
  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
  • 原文地址:https://www.cnblogs.com/a821403286/p/13693411.html
Copyright © 2011-2022 走看看