zoukankan      html  css  js  c++  java
  • 最小生成树——Kruskal算法(C++)

    源代码:
    
    #include<cstdio>
    int f[1001],xxx[1001],yyy[1001],i[1001],m,n,k(0);
    long long ans(0);
    void x1(int t1,int t2)
    {
        int x=t1,y=t2,m=i[(t1+t2)/2],t;
        do
        {
          while (i[x]<m)
            x++;
          while (i[y]>m)
            y--;
          if (x<=y)
          {
            t=i[x];
            i[x]=i[y];
            i[y]=t;
            t=xxx[x];
            xxx[x]=xxx[y];
            xxx[y]=t;
            t=yyy[x];
            yyy[x]=yyy[y];
            yyy[y]=t;
            x++;
            y--;
          }
        }
        while (x<=y);
        if (x<t2)
          x1(x,t2);
        if (y>t1)
          x1(t1,y);
    }
    int x2(int t)
    {
        if (f[t]==0)
          return t;
        f[t]=x2(f[t]);
        return f[t];
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for (int a=1;a<=m;a++)
          scanf("%d%d%d",&xxx[a],&yyy[a],&i[a]);
        x1(1,m);
        for (int a=1;a<=m;a++)
        {
          int t1,t2;
          t1=x2(xxx[a]);
          t2=x2(yyy[a]);
          if (t1!=t2)
          {
            k++;
            if (k==n)
              break;  //节点计数器,以节省时间。
            f[t2]=t1;
            ans+=i[a];
          }  //利用并查集对快排完的权值进行不同集合合并处理。
        }
        printf("%d",ans);
        return 0;
    }
  • 相关阅读:
    关于checkbox的一篇博客
    如何快速学习
    for循环下的取值问题
    vue的自动更新原理
    关于word-wrap的用法;
    2016年百度面试题
    编写代码的原则
    null和defined的区别
    js的模块化加载
    springmvc注解
  • 原文地址:https://www.cnblogs.com/koruko/p/5100358.html
Copyright © 2011-2022 走看看