首页 > 其他 > 详细

P1546 最短网络(kruscal+并查集)

时间:2020-01-26 11:35:07      阅读:82      评论:0      收藏:0      [点我收藏+]

从邻接矩阵中提取出边,然后跑一边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 }

 

P1546 最短网络(kruscal+并查集)

原文:https://www.cnblogs.com/greenofyu/p/12233887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!