N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。

 
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
Output示例
37
#include <algorithm>
#include <iostream>
#include <cstdio> using namespace std;
struct node
{
int x,y,z;
}edge[];
int tot,fa[],i,j,n,m;
int find_fa(int x)
{
if(fa[x]==x)
return x;
else return find_fa(fa[x]);
}
bool cmp(node a,node b)
{
return a.z<b.z;
}
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
int s,e,w;
for(i=;i<m;++i)
{
cin>>s>>e>>w;
tot++;
edge[tot].x=s;
edge[tot].y=e;
edge[tot].z=w;
}
for(i=;i<=n;++i) fa[i]=i;
sort(edge+,edge++tot,cmp);
int ans=,h=;
for(i=;i<=tot;++i)
{
int x=find_fa(edge[i].x),y=find_fa(edge[i].y);
if(x!=y)
{
h++;
fa[y]=x;
ans+=edge[i].z;
if(h==n-)
break;
}
}
cout<<ans;
}

最新文章

  1. MFC2016.6.8
  2. svn的牛逼操作反向merge
  3. sql case 用法总结
  4. 分布式缓存技术redis学习系列(一)——redis简介以及linux上的安装
  5. Java框架介绍-13个不容错过的框架项目
  6. mysql 用sql 语句去掉某个字段重复值数据的方法
  7. 如何将Mac OS X10.9下的Python2.7升级到最新的Python3.3
  8. DOM(二)使用DOM
  9. iOS 如何优雅的处理“回调地狱Callback hell”(一) (下)
  10. 最简单的修改HashMap value值的方法
  11. kindeditor图片上传 struts2实现
  12. 实时消息传输协议(RTMP)详解
  13. 张高兴的 Xamarin.Forms 开发笔记:为 Android 与 iOS 引入 UWP 风格的汉堡菜单 ( MasterDetailPage )
  14. 重启mysql主从同步mongodb(tungsten-replicator)
  15. 放yy直播点赞动画
  16. 快速导入导出Oracle数据demo(sqlldr、UTL_FILE)
  17. 【PyQt5-Qt Designer】日历(QCalendarWidget)
  18. H5手机移动端调起浏览器(qq浏览器,uc浏览器)自带分享功能实例
  19. Codeforces Round #516 (Div. 2, by Moscow Team Olympiad) D. Labyrinth(重识搜索)
  20. windows 8 中 使用 httpclient

热门文章

  1. 【网络爬虫】【java】微博爬虫(五):防止爬虫被墙的几个技巧(总结篇)
  2. maven构建java项目、web项目
  3. C#基础:线程之异步回调(委托)
  4. mock api
  5. 洛谷 - P2278 - 操作系统 - 模拟
  6. 1004 Counting Leaves (30 分)
  7. 51nod 1416【DFS】
  8. POJ3414(BFS+[手写队列])
  9. Sublime Text 报“Pylinter could not automatically determined the path to lint.py
  10. Java | 基础归纳 | Map.Entry&lt;String, String&gt;