zoukankan      html  css  js  c++  java
  • P1546 最短网络(kruscal+并查集)

    从邻接矩阵中提取出边,然后跑一边kruscal

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 struct node
     5 {
     6     int x,y,w;
     7 };
     8 int cnt=0;//记录边数
     9 node a[100*100];//记录边
    10 int fa[110];//记录并查集
    11 int finds(int x)//并查集找祖先
    12 {
    13     while(fa[x]!=x)
    14     {
    15         x=fa[x];
    16     }
    17     return x;
    18 }
    19 bool cmp(node a,node b)
    20 {
    21     return a.w<b.w;
    22 }
    23 int main(void)
    24 {
    25     int n;
    26     cin>>n;
    27     for(int i=1;i<=n;i++)//提取边
    28     {
    29         for(int j=1;j<=n;j++)
    30         {
    31             int t;
    32             cin>>t;
    33             if(j>i)//如果列大于行
    34             {
    35                 a[cnt].x=i;
    36                 a[cnt].y=j;
    37                 a[cnt].w=t;
    38                 cnt++;
    39             }
    40         }
    41     }
    42     sort(a,a+cnt,cmp);//排序
    43     //以上处理边
    44     for(int i=1;i<=n;i++)
    45     {
    46         fa[i]=i;
    47     }//初始化并查集
    48     int res=0;
    49     for(int i=0;i<cnt;i++)//找最小生成树
    50     {
    51         int from=a[i].x;
    52         int to=a[i].y;
    53         int weight=a[i].w;
    54         int f1=finds(from);
    55         int f2=finds(to);
    56         if(f1!=f2)
    57         {
    58             res+=weight;
    59             fa[f1]=f2;//union
    60         }
    61     }
    62     cout<<res;
    63     return 0;
    64 }
  • 相关阅读:
    PHP比较操作符
    一个给图片加水印的程序
    PHP开发人员:充实您的XML工具箱
    PHP时间函数
    (Oralce)Web翻页优化实例
    PHP文件操作函数
    PHP图象函数
    PHP逻辑操作符
    PHP位操作符
    PHP目录遍历函数
  • 原文地址:https://www.cnblogs.com/greenofyu/p/12233887.html
Copyright © 2011-2022 走看看