2021-04-19:手写代码:最小生成树算法之Kruskal。

福大大 答案2021-04-19:

并查集。边从小到大,找最小边,无环。

代码用golang编写。代码如下:

package main

import (
"fmt"
"sort"
) func main() {
graph := &Graph{}
graph.nodes = make(map[int]*Node)
graph.nodes[0] = &Node{}
graph.nodes[1] = &Node{}
graph.nodes[2] = &Node{} graph.edges = make(map[*Edge]struct{})
graph.edges[&Edge{weight: 22, from: graph.nodes[0], to: graph.nodes[1]}] = struct{}{}
graph.edges[&Edge{weight: 33, from: graph.nodes[1], to: graph.nodes[2]}] = struct{}{}
graph.edges[&Edge{weight: 11, from: graph.nodes[2], to: graph.nodes[0]}] = struct{}{}
ret := kruskalMST(graph)
fmt.Println("结果:")
for a, _ := range ret {
fmt.Println(a.weight)
}
} type Edge struct {
weight int
from *Node
to *Node
} // 点结构的描述
type Node struct {
value int
in int
out int
nexts []*Node
edges []*Edge
}
type Graph struct {
nodes map[int]*Node
edges map[*Edge]struct{}
} func printPriorityQueue(priorityQueue []*Edge) {
for _, edge := range priorityQueue {
fmt.Println(edge.weight)
}
} func kruskalMST(graph *Graph) map[*Edge]struct{} {
unionFind := &UnionFind{}
unionFind.makeSets(graph.nodes)
// 从小的边到大的边,依次弹出,小根堆!
priorityQueue := make([]*Edge, 0)
for edge, _ := range graph.edges {
priorityQueue = append(priorityQueue, edge)
}
fmt.Println("排序前:")
printPriorityQueue(priorityQueue)
//排序
sort.SliceStable(priorityQueue, func(i int, j int) bool {
return priorityQueue[i].weight > priorityQueue[j].weight
})
fmt.Println("--------")
fmt.Println("排序后:")
printPriorityQueue(priorityQueue)
fmt.Println("--------")
result := make(map[*Edge]struct{})
for len(priorityQueue) > 0 { // M 条边
edge := priorityQueue[len(priorityQueue)-1]
priorityQueue = priorityQueue[0 : len(priorityQueue)-1]
if !unionFind.isSameSet(edge.from, edge.to) { // O(1) result[edge] = struct{}{}
unionFind.union(edge.from, edge.to)
}
}
return result
} type UnionFind struct {
// key 某一个节点, value key节点往上的节点
fatherMap map[*Node]*Node
// key 某一个集合的代表节点, value key所在集合的节点个数
sizeMap map[*Node]int
} func (this *UnionFind) makeSets(nodes map[int]*Node) {
this.fatherMap = make(map[*Node]*Node)
this.sizeMap = make(map[*Node]int)
for _, node := range nodes {
this.fatherMap[node] = node
this.sizeMap[node] = 1
}
} func (this *UnionFind) findFather(n *Node) *Node {
path := make([]*Node, 0)
for n != this.fatherMap[n] {
path = append(path, n)
n = this.fatherMap[n]
}
for len(path) > 0 { this.fatherMap[path[len(path)-1]] = n
path = path[0 : len(path)-1]
}
return n
} func (this *UnionFind) isSameSet(a *Node, b *Node) bool {
return this.findFather(a) == this.findFather(b)
} func (this *UnionFind) union(a *Node, b *Node) {
if a == nil || b == nil {
return
}
aDai := this.findFather(a)
bDai := this.findFather(b)
if aDai != bDai {
aSetSize := this.sizeMap[aDai]
bSetSize := this.sizeMap[bDai]
if aSetSize <= bSetSize {
this.fatherMap[aDai] = bDai
this.sizeMap[bDai] = aSetSize + bSetSize
delete(this.sizeMap, aDai)
} else {
this.fatherMap[bDai] = aDai
this.sizeMap[aDai] = aSetSize + bSetSize
delete(this.sizeMap, bDai)
}
}
}

执行结果如下:


左神java代码

2021-04-19:手写代码:最小生成树算法之Kruskal。的更多相关文章

  1. .netER的未来路,关于基础是否重要和应该自己手写代码吗?

    http://www.cnblogs.com/onepiece_wang/p/5558341.html#!comments 引用"基础知识的学习,一开始可能是背书,但是在后续若干年的工作过程 ...

  2. ClownFish:比手写代码还快的通用数据访问层

    http://www.cnblogs.com/fish-li/archive/2012/07/17/ClownFish.html 阅读目录 开始 ClownFish是什么? 比手写代码还快的执行速度 ...

  3. 手写代码自动实现自动布局,即Auto Layout的使用

    手写代码自动实现自动布局,即Auto Layout的使用,有需要的朋友可以参考下. 这里要注意几点: 对子视图的约束,若是基于父视图,要通过父视图去添加约束. 对子视图进行自动布局调整,首先对UIVi ...

  4. 如果选择构建ui界面方式,手写代码,xib和StoryBoard间的博弈

    代码手写UI这种方法经常被学院派的极客或者依赖多人合作的大型项目大规模使用. 大型多人合作项目使用代码构建UI,主要是看中纯代码在版本管理时的优势,检查追踪改动以及进行代码合并相对容易一些. 另外,代 ...

  5. 手写代码UI,xib和StoryBoard间的的优劣比较

    在UI制作方面,逐渐分化三种主要流派:使用代码手写UI:使用单个xib文件组织viewController或者view:使用StoryBoard来通过单个或很少的几个文件构建UI.三种方式各有优劣,也 ...

  6. UI到底应该用xib/storyboard完成,还是用手写代码来完成?

    UI到底应该用xib/storyboard完成,还是用手写代码来完成? 文章来源:http://blog.csdn.net/libaineu2004/article/details/45488665 ...

  7. 2019前端面试系列——JS高频手写代码题

    实现 new 方法 /* * 1.创建一个空对象 * 2.链接到原型 * 3.绑定this值 * 4.返回新对象 */ // 第一种实现 function createNew() { let obj ...

  8. Appium初始化设置:手写代码连接手机、appium-desktop连接手机

    一.包名获取的三种方式 1)找开发要2)mac使用命令:adb logcat | grep START win使用命令:adb logcat | findstr START 或者可以尝试使用第3条命令 ...

  9. gcd手写代码及STL中的使用方法

    一.手写代码 inline int gcd(int x,int y){ if(y==0) return x; else return(gcd(y,x%y)); } 二.STL中的使用方法 注:在STL ...

  10. SpringCloud-Ribbon负载均衡机制、手写轮询算法

    Ribbon 内置的负载均衡规则 在 com.netflix.loadbalancer 包下有一个接口 IRule,它可以根据特定的算法从服务列表中选取一个要访问的服务,默认使用的是「轮询机制」 Ro ...

随机推荐

  1. 脏牛-Linux内核提权

    漏洞范围 下载地址:https://github.com/FireFart/dirtycow 有一点可以在意,dirty.c内置在了kali中,使用命令searchsploit dirty可以搜索 也 ...

  2. Nacos的微服务与本地测试的问题

    前提条件: 这里是微服务上的yml的配置: uri: base-svc-authcenter: 192.168.1.121:28002 base-svc-file: 192.168.1.121:280 ...

  3. 除select外查询数据的另一种姿势

    1.24 1.[GYCTF2020]Blacklist buuctf上的题目 1.解题过程 输入1会返回一个数组,加上单引号就报错了,说明存在注入 以前做过类似的估计是堆叠注入,尝试一下 注入成功 正 ...

  4. 浅谈云原生基础入坑与docker 搭建redis-cluster集群

    浅谈云原生基础入坑与docker 搭建redis-cluster集群 开篇来点自己的小感触:自从走上后端开发这条无法回头的互卷道路以后,在视野内可见新的技术在迭代,更新的技术在不断发行.就拿最近的Op ...

  5. [C++STL教程]6.bitset是什么?和bool有什么区别?零基础都能看懂的入门教程

    之前我们介绍过vector, queue, stack,map,set,今天我们介绍另外一个stl容器:bitset. 作者:Eriktse 简介:19岁,211计算机在读,现役ACM银牌选手力争以通 ...

  6. Nebius Welcome Round (Div. 1 + Div. 2) 题解 A - D

    Nebius Welcome Round (Div. 1 + Div. 2) 题解 A - D,这四题的整体难度不大,都是过题人数上千的题. 很久没打Codeforces了,在此记录一篇题解,开学了也 ...

  7. 机器学习基础04DAY

    scikit-learn数据集 我们将介绍sklearn中的数据集类,模块包括用于加载数据集的实用程序,包括加载和获取流行参考数据集的方法.它还具有一些人工数据生成器. sklearn.dataset ...

  8. 7.远程代码执行漏洞RCE

    远程代码执行漏洞RCE 1.RCE Remote Code Execute 远程代码执行 Remote Command Execute 远程命令执行 2.危害 窃取服务器的敏感数据.文件 对电脑的文件 ...

  9. Rainbond的 Gateway API 插件制作实践

    Gateway API 作为新一代的流量管理标准,对原有 Ingress 的扩展不规范.移植性差等问题做出了改进.从兼容K8s生态和优化网关体验出发,Rainbond 支持以插件的形式扩展平台网关能力 ...

  10. ML-程序练习-Dragon

    回归问题 前期 假设已有某样例,参数为w=1.477, b=0.089,即为\(y=1.477x+0.089\) 过程分析 数据采样 首先我们需要模拟一些带有真实样本观测误差的数据(因为真实情况是真实 ...