51nod 1212 无向图最小生成树(Kruskal模版题)
2024-08-30 10:56:42
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;
}
最新文章
- MFC2016.6.8
- svn的牛逼操作反向merge
- sql case 用法总结
- 分布式缓存技术redis学习系列(一)——redis简介以及linux上的安装
- Java框架介绍-13个不容错过的框架项目
- mysql 用sql 语句去掉某个字段重复值数据的方法
- 如何将Mac OS X10.9下的Python2.7升级到最新的Python3.3
- DOM(二)使用DOM
- iOS 如何优雅的处理“回调地狱Callback hell”(一) (下)
- 最简单的修改HashMap value值的方法
- kindeditor图片上传 struts2实现
- 实时消息传输协议(RTMP)详解
- 张高兴的 Xamarin.Forms 开发笔记:为 Android 与 iOS 引入 UWP 风格的汉堡菜单 ( MasterDetailPage )
- 重启mysql主从同步mongodb(tungsten-replicator)
- 放yy直播点赞动画
- 快速导入导出Oracle数据demo(sqlldr、UTL_FILE)
- 【PyQt5-Qt Designer】日历(QCalendarWidget)
- H5手机移动端调起浏览器(qq浏览器,uc浏览器)自带分享功能实例
- Codeforces Round #516 (Div. 2, by Moscow Team Olympiad) D. Labyrinth(重识搜索)
- windows 8 中 使用 httpclient
热门文章
- 【网络爬虫】【java】微博爬虫(五):防止爬虫被墙的几个技巧(总结篇)
- maven构建java项目、web项目
- C#基础:线程之异步回调(委托)
- mock api
- 洛谷 - P2278 - 操作系统 - 模拟
- 1004 Counting Leaves (30 分)
- 51nod 1416【DFS】
- POJ3414(BFS+[手写队列])
- Sublime Text 报“Pylinter could not automatically determined the path to lint.py
- Java | 基础归纳 | Map.Entry<;String, String>;