克鲁斯卡尔(Kruskal)算法求最小生成树
2024-10-18 22:25:41
/*
*Kruskal算法求MST
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <stack>
using namespace std; const int MAXN = 110; //最大点数
const int MAXM = 10000; //最大边数
int F[MAXN]; //并查集使用 struct Edge {
int u, v, w;
}edge[MAXM]; //存储边的信息,包括起点/终点/权值 int tol = 0; //记录边数 void addedge(int u, int v, int w) {
edge[tol].u = u;
edge[tol].v = v;
edge[tol++].w = w;
} bool cmp(Edge a, Edge b) { //排序函数,将边按照权值从小到大排序
return a.w < b.w;
} int find(int x) {
if (F[x] == -1)
return x;
else
return F[x] = find(F[x]);
} int Kruskal(int n) { //传入点数,返回最小生成树的权值,如果不连通返回-1
memset(F, -1, sizeof(F));
sort(edge, edge+tol, cmp);
int cnt = 0; //计算加入的边数
int ans = 0;
for (int i = 0; i<tol; i++) {
int u = edge[i].u;
int v = edge[i].v;
int w = edge[i].w;
int t1 = find(u);
int t2 = find(v);
if (t1 != t2) {
ans += w;
F[t1] = t2;
cnt ++ ;
}
if (cnt == n-1)
break;
}
if (cnt < n-1)
return -1;
else
return ans;
} int main() {
int t;
cin >> t;
while (t --) {
tol = 0;
memset(edge, 0, sizeof(edge));
int n, m;
cin >> n >> m;
while (m --) {
int x, y, w;
cin >> x >> y>> w;
addedge(x, y, w);
}
int res = Kruskal(tol);
if (res == -1)
cout << "Not Unique!"<< endl;
else
cout << res << endl; }
return 0;
}
最新文章
- [ASP.NET MVC 小牛之路]15 - Model Binding
- 【转】【51CTO 网+】怎样做一款让用户来电的产品
- C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 角色权限的配置页面改进优化
- mui,css3 querySelector,appendChild,style.display,insertBefore
- android中string.xml中%1$s、%1$d等的用法
- python学习之——小闹钟(持续完善ing)
- GoodsAndStaffManagermentSystem----Sprint 计划1
- Create Stacked Canvas to Scroll Horizontal Tabular Data Blocks In Oracle Forms
- 【LeetCode】198 - House Robber
- PS拾色器(前景色背景色)快捷键
- svn命令操作
- Oracle 11g 新特性(一)-- 虚拟列
- scss组件定制的一些学习
- Event对象的事件句柄
- [Paper Reading]--Exploiting Relevance Feedback in Knowledge Graph
- ASP.NET 控制器
- 【经验随笔】Java程序远程调试定位特定运行环境上出现的问题
- 【spring实战第五版遇到的坑】3.1中的例子报错
- jmeter接口测试实例1-添加学生信息
- The last packet sent successfully to the server was 0 milliseconds ago.[nutch---mysql ]
热门文章
- bzoj 1196: [HNOI2006]公路修建问题
- .net 连接SqlServer数据库及基本增删改查
- 用js筛选数据排序
- 4.Nginx的URL重写应用
- 欢迎大家走进我的园子 ( ^___^ )y 本博客文章目录整理
- js构建函数优秀案例
- js、jQuery、layer实现弹出层的打开、关闭
- iOS使用带字体图标的UIButton(支持各种方向)
- Git详解之一:Git起步
- iOS中的armv7,armv7s,arm64,i386,x86_64