简单的最小生成树1078
2014-08-01 16:51
176 查看
1078 最小生成树
题目描述 Description农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。 约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了使花费最少,他想铺设最短的光纤去连接所有的农场。 你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。 每两个农场间的距离不会超过100000
输入描述 Input Description
第一行: 农场的个数,N(3<=N<=100)。
第二行..结尾: 接下来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们每行限制在80个字符以内,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为线路从第i个农场到它本身的距离在本题中没有意义。
输出描述 Output Description
只有一个输出,是连接到每个农场的光纤的最小长度和。
样例输入 Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
样例输出 Sample Output
28
分析:对输入稍作处理一下,按照一对村庄和之间距离的方式保存起来,再从小到大排列一下,然后合并,可以合并的距离累加一下。
#include<cstdio> #include<algorithm> using namespace std; const int maxn = 10000 + 10; int p[maxn]; struct Line{ int a, b, len; bool operator < (const Line& x) const{//重载操作符 if(len < x.len) return true; return false; } }line[maxn]; int Find(int x){ return p[x] == x ? x : p[x] = Find(p[x]);//查找 } bool Union(int x, int y){//合并 x = Find(x); y = Find(y); if(x != y){ p[x] = y; return true;//合并成功 } return false; } int main(){ int n, temp, k = 0, sum = 0; scanf("%d", &n); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++){ scanf("%d", &temp); if(i == j) continue;//减少储存量 line[k].a = i; line[k].b = j; line[k++].len = temp; } sort(line, line + k);//排序 for(int i = 0; i <= n; i++) p[i] = i; for(int i = 0; i < k; i++) if(Union(line[i].a, line[i].b)) sum += line[i].len;//若合并成功,累加其和 printf("%d\n", sum); return 0; }
相关文章推荐
- ACM HDU 1301 Jungle Roads (简单最小生成树问题)
- ACM POJ 2421 Constructing Roads(简单最小生成树)
- 【wikioi】1078最小生成树 floyd 40分C源码
- hdoj 畅通工程(简单最小生成树问题)
- wikioi 1078 最小生成树
- POJ1258 Agri-Net(简单的prim最小生成树)
- POJ 2421 Constructing Roads(简单最小生成树)
- POJ 2031 Building a Space Station 简单计算几何 + 最小生成树
- poj——1789(图论之最小生成树的简单应用)
- nyoj 38 简单并查集的应用&最小生成树
- hdu 1879 简单最小生成树
- 最小生成树问题 普利姆算法简单模板 hdoj1233
- poj1789Truck History(简单最小生成树)
- poj 1258 Agri-Net(简单最小生成树)
- POJ 1789 Truck History【最小生成树简单应用】
- ACM POJ 1258 Agri-Net (简单最小生成树)
- poj (简单题:kruskal判断最小生成树是否唯一--求次小生成树 )
- POJ 2485 Highways【最小生成树最大权——简单模板】
- 【wikioi】1078最小生成树 floyd 改 仍40分代码
- nyoj 38 简单并查集的应用&最小生成树