zoukankan      html  css  js  c++  java
  • 【洛谷 3366】最小生成树_Kruskal

    题目描述

    如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出orz

    输入格式

    第一行包含两个整数N、M,表示该图共有N个结点和M条无向边。(N<=5000,M<=200000)

    接下来M行每行包含三个整数Xi、Yi、Zi,表示有一条长度为Zi的无向边连接结点Xi、Yi

    输出格式

    输出包含一个数,即最小生成树的各边的长度之和;如果该图不连通则输出orz

    输入输出样例

    输入 #1
    4 5
    1 2 2
    1 3 2
    1 4 3
    2 3 4
    3 4 3
    输出 #1
    7

    说明/提示

    时空限制:1000ms,128M

    数据规模:

    对于20%的数据:N<=5,M<=20

    对于40%的数据:N<=50,M<=2500

    对于70%的数据:N<=500,M<=10000

    对于100%的数据:N<=5000,M<=200000

    样例解释:

    所以最小生成树的总边权为2+2+3=7

    题解:最小生成树

    首先按照边权值从小到大排序。然后找环。如果u,v,不在同一个集合里,就更新操作。

    答案加上边权值。如果已经有n-1条边构成了最小生成树,退出即可。

    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<cmath>
    #include<cstring>
    #include<cstdlib>
    #include<cstdio>
    using namespace std;
    const int N=400005;
    int n,ans,m,biu;
    struct node{
        int uu,vv,w;
    }e[N];
    int dis[N],head[N],cnt,fa[N];
    bool vis[N];
    bool cmp(node a,node b){
        return a.w<b.w;
    }
    int find(int x){
        if(x!=fa[x]) fa[x]=find(fa[x]);
        return fa[x];
    }
    
    
    void init(){
        scanf("%d %d",&n,&m);
        for(int i=1;i<=n;i++) fa[i]=i;
        
        for(int i=1;i<=m;i++)
            scanf("%d %d %d",&e[i].uu,&e[i].vv,&e[i].w);
    }
    void Yao_Chen_Lai_Le(){
        int u,v;
        sort(e+1,e+m+1,cmp);
        for(int i=1;i<=m;i++){
            u=find(e[i].uu);
            v=find(e[i].vv);
            if(u==v) continue;
            ans+=e[i].w;
            fa[u]=v; biu++;
            if(biu==(n-1)) break;
        }
    }
    int main(){
        freopen("k3366.in","r",stdin);
        freopen("k3366.out","w",stdout);
        init();
        Yao_Chen_Lai_Le();
        printf("%d",ans);
        return 0;
    }
  • 相关阅读:
    python subprocess.Popen 非阻塞
    linux错误码
    python中logging
    python多线程和多进程对比
    python多进程提高cpu利用率
    django orm 操作
    linux故障判断
    linux中软链接打包、计算以及同步
    小程序收集formid跳转后收集不到
    Git Base 操作(二)
  • 原文地址:https://www.cnblogs.com/wuhu-JJJ/p/11289051.html
Copyright © 2011-2022 走看看