zoukankan      html  css  js  c++  java
  • 最小生成树,并查集的思想 nyoj1239

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    
    using namespace std;
    
    int n,pre[10010],cnt;
    struct node
    {
        int x,y;
        int val;
    } p[10010];
    void init()
    {
        for(int i=0; i<10010; i++)
            pre[i]=i;
    }
    int cmp(node s1,node s2)
    {
        return s1.val<s2.val;
    }
    int find(int x)
    {
        return x==pre[x]?x:find(pre[x]);
    }
    int join(int x,int y)
    {
        int fx=find(x);
        int fy=find(y);
        if(fx!=fy)
        {
            pre[fx]=fy;
            return 1;
        }
        return 0;
    }
    int main()
    {
        int t;
        scanf("%d",&t);
        while(t--)
        {
            init();
            cnt=0;
            scanf("%d",&n);
            for(int i=0; i<=n; i++)
            {
                for(int j=1; j<=n; j++)
                {
                    scanf("%d",&p[cnt].val);
                    p[cnt].x=i,p[cnt++].y=j;
                }
            }
            sort(p,p+cnt,cmp);
            int sum=0;
            for(int i=0; i<cnt; i++)
            {
                if(join(p[i].x,p[i].y))
                    sum+=p[i].val;
            }
            printf("%d
    ",sum);
        }
        return 0;
    }
    

  • 相关阅读:
    HashSet源码分析
    Mysql的体系结构和存储引擎
    触发器
    存储过程和函数
    索引
    SpringBoot 中的日志使用
    log4j2
    Logback
    slf4j
    日志门面
  • 原文地址:https://www.cnblogs.com/coded-ream/p/7208010.html
Copyright © 2011-2022 走看看