C++——克鲁斯卡尔模板
来源:互联网 发布:东安格利亚大学 知乎 编辑:程序博客网 时间:2024/05/24 04:33
题目描述
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过 100000。
输入格式
第一行:农场的个数 N(3<=N<=1000)。
第二行..结尾:包含了一个 N * N 的矩阵,表示每个农场之间的距离(不超过100000)。理论上,他们是 N 行,每行由 N 个用空格分隔的数组成,实际上,他们限制在 80 个字符,因此,某些行会紧接着另一些行。当然,对角线将会是 0,因为不会有线路从第 i 个农场到它本身。
输出格式
输出一个整数,表示连接到每个农场的光纤的最小长度。
样例数据 1
输入 [复制]
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
输出
28
//克鲁斯卡尔算法求最小生成树 #include<iostream>#include<cstdio>#include<algorithm>#include<cmath>#include<cstdlib>#include<string>#include<cstring>#include<ctime>using namespace std;struct bian { int x; //边的起点 int y; //边的终点 int w; //边的长度 };bian a[20000]; //a[i]存储第i条边的信息 int father[201]; //father[i]表示第i个点的根 int n,i,j,x,m,tot,k; //tot存储最小生成树边的总长度(最小的);m是边的数量 bool comp(const bian &a,const bian &b) //自设比较函数 { return a.w<b.w; //按边的长度从小到大排序 }int getfather(int x) //找x的根 { if (father[x]==x) return x; father[x]=getfather(father[x]); return father[x];}void unionn(int x,int y) //把x、y合并到一个连通块 { int fa,fb; fa=getfather(x); fb=getfather(y); if (fa!=fb) father[fa]=fb;} int main(){ freopen("agrinet.in","r",stdin); freopen("agrinet.out","w",stdout); scanf("%d",&n); //读入点的数量n m=0; for(i=1;i<=n;i++) //存储每条边 for(j=1;j<=n;j++) { scanf("%d",&x); if(x!=0) { m++; //累加边的数量 a[m].x=i; //存第m条边的起点 a[m].y=j; //存第m条边的终点 a[m].w=x; //存第m条边的长度 } } for(i=1;i<=n;i++) father[i]=i; //初始化:每个点单独是一个联通块 sort(a+1,a+m+1,comp); //按边的长度从小到大排序 for(i=1;i<=m-1;i++) //Kruskal算法,依次处理每一条边 { if(getfather(a[i].x)!=getfather(a[i].y)) //如果第i条边的两个端点不在一个联通块中 { unionn(a[i].x,a[i].y); //合并第i条边的两个点 tot=tot+a[i].w; //累加最小生成树长度 k++; //计算生成树中边的数量 } if(k==n-1) break; //如果已经加入了n-1条边,则最小生成树建立完成 } printf("%d\n",tot); return 0;}
0 0
- C++——克鲁斯卡尔模板
- 克鲁斯卡尔算法(Kruskal)模板
- c语言之克鲁斯卡尔算法
- C语言-数据结构-克鲁斯卡尔kruskal
- 最小生成树——克鲁斯卡尔
- HDOJ 1863 畅通工程——克鲁斯卡尔算法
- POJ 1258 ——Agri-Net 克鲁斯卡尔算法
- Swordfish (最小生成树——克鲁斯卡尔方法)
- 最小生成树—克鲁斯卡尔算法
- 最小生成树算法—Prim和克鲁斯卡尔
- 克鲁斯卡尔算法
- 克鲁斯卡尔总结
- Kruskal(克鲁斯卡尔)
- 克鲁斯卡尔算法
- 克鲁斯卡尔算法
- 克鲁斯卡尔算法
- 克鲁斯卡尔模版
- 克鲁斯卡尔算法
- ubuntu14.04/ubuntu10.04/ubuntu16.04中文乱码Gedit中文乱码
- android studio模块化开发
- 数据库表格行和列倒置
- QT 界面美化
- 系统函数解释
- C++——克鲁斯卡尔模板
- struts2输入校验
- Caused by: java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Date
- java开发规范
- js 获取php 变量
- python 调用shell命令的方法
- imageview 设置圆角
- C语言QueryPerformanceFrequency和QueryPerformanceCounter的用法
- shell 获取 postgresql返回字段值