图论——Dijkstra+prim算法涉及到的优先队列(二叉堆)

【0】README

0.1)为什么有这篇文章?因为 Dijkstra算法的优先队列实现 涉及到了一种新的数据结构,即优先队列(二叉堆)的操作需要更改以适应这种新的数据结构,我们暂且吧它定义为Distance, 而不是单纯的int类型;
0.2)本文源代码均为原创, int类型的优先队列(二叉堆)的操作实现,参见http://blog.csdn.net/PacosonSWJTU/article/details/49498255, (并比较他们的打印结果,很有必要)


【1】因为 Dijkstra算法的优先队列实现, 需要用到二叉堆的相关操作,但是操作的元素类型(ElementType 不是 单纯的int类型), 而是如下:

struct Distance
{int vertexIndex; //当前顶点下标int distance; //初始顶点到当前顶点的distance
};

【2】看个荔枝

2.1)需要特别说明的是: indexOfVertexInHeap 数组记录的是顶点vertex在 heap中的位置, 如 indexOfVertexInHeap [1] = 4;表明heap的第4个位置记录这 编号为1的vertex;
2.2)优先队列的insert和deleteMin 的执行演示(请将我的手动演示结果同我的代码打印结果做对比,经过对比,你发现它们的效果是一致的,恰好说明了我的代码的可行性):

Attention)

  • A1)其实本文中的二叉堆优先队列的实现源代码和 int类型的优先队列源代码类似,只不过它们操作的数据类型不一样罢了,当然, 这只需要简单的修改即可;
  • A2)打印结果在文末,可以看到,ElementType采用int 和 Distance的打印效果一样,这正证明了我们采用Distance结构体对源码的修改是无误的,相比于单纯的int 类型,只不过Distance又多了一个 顶点下标vertexIndex成员变量而已;

【3】source code + printing results

3.1)download source code:
https://github.com/pacosonTang/dataStructure-algorithmAnalysis/tree/master/chapter9/binaryHeap_dijkstra_prim
3.2)source code at a glance:(for complete code , please click the given link above)

1st file:distance.h

#include <stdio.h>#define Error(str) printf("\n error: %s \n",str)   struct Distance;
typedef struct Distance *Distance;
struct Distance
{int vertexIndex;int distance;
};Distance makeEmptyDistance();

2nd file:distance.c

#include "distance.h"
#include <malloc.h>// allocate the memory for Distance struct
Distance makeEmptyDistance()
{Distance element;element = (Distance)malloc(sizeof(struct Distance));if(!element){Error("out of space ,from func makeEmptyDistance");return NULL;}       return element;
}

3rd file:binaryheap.h

#include <stdio.h>
#include <malloc.h>
#include "distance.h"#define ElementType Distance#define Error(str) printf("\n error: %s \n",str)   struct BinaryHeap;
typedef struct BinaryHeap *BinaryHeap;void swap(ElementType x, ElementType y);
BinaryHeap initBinaryHeap(int capacity);
void insert(ElementType value, BinaryHeap bh, int*);
ElementType deleteMin(BinaryHeap, int*);
int isFull(BinaryHeap bh);
int isEmpty(BinaryHeap bh);
void percolateUp(int index, BinaryHeap bh);
void percolateDownFromOne(int index, BinaryHeap bh, int*);
void printBinaryHeap(BinaryHeap bh);
void printBinaryHeapFromZero(BinaryHeap bh);struct BinaryHeap 
{int capacity;int size;   ElementType *elements;      
};

4th file:binaryheap.c

#include "binaryheap.h"
#include <math.h>#define MaxInt (int)pow(2, 16)
//judge whether the BinaryHeap is full or not , also 1 or 0 
int isFull(BinaryHeap bh)
{return bh->size == bh->capacity - 1; 
}//judge whether the BinaryHeap is empty or not , also 1 or 0 
int isEmpty(BinaryHeap bh)
{return bh->size == 0;
}// get the left child of node under index with startup 1
int leftChildFromOne(int index)
{return index * 2;
}void printBinaryHeap(BinaryHeap bh)
{int i;ElementType *temp;if(!bh)Error("printing execution failure, for binary heap is null, from func printBinaryHeap");    temp = bh->elements;for(i = 1; i < bh->capacity; i++){printf("\n\t heap[%d] = ", i);if(i <= bh->size)printf("vertex[%d] + distance[%d]", bh->elements[i]->vertexIndex+1, bh->elements[i]->distance);     elseprintf("NULL");}printf("\n");   
}  //print the binary heap who starts from index 0
void printBinaryHeapFromZero(BinaryHeap bh)
{int i;ElementType *temp;if(!bh)Error("printing execution failure, for binary heap is null, from func printBinaryHeap");    temp = bh->elements;for(i = 0; i < bh->capacity; i++){printf("\n\t index[%d] = ", i);if(i < bh->size)printf("%d", bh->elements[i]->distance);elseprintf("NULL");}printf("\n");
}  void swap(ElementType x, ElementType y)
{struct Distance temp;temp = *x;*x = *y;*y = temp;  
}ElementType deleteMin(BinaryHeap bh, int* heapIndexRecord)
{   ElementType minimum;ElementType *data;  if(isEmpty(bh)){Error("failed deleting minimum , for the BinaryHeap is empty, from func deleteMin !");return NULL;    }data = bh->elements;     minimum = data[1];swap(data[1], data[bh->size]);      bh->size-- ; // size-- occurs prior to percolateDownFromOne percolateDownFromOne(1, bh, heapIndexRecord) ;  return minimum;
} // percolating down the element when its value is greater than children (minimal heap)//Attention: all of bh->elements starts from index 1void percolateDownFromOne(int index, BinaryHeap bh, int* heapIndexRecord){  ElementType *data;int size;struct Distance temp;int child;data = bh->elements;size = bh->size;    for(temp = *data[index]; leftChildFromOne(index) <= size; index = child){child = leftChildFromOne(index);if(child < size && data[child]->distance > data[child+1]->distance)child++;if(temp.distance > data[child]->distance){           *data[index] = *data[child];            heapIndexRecord[bh->elements[index]->vertexIndex] = index; //update the heapIndexRecord}elsebreak;}   *data[index] = temp;    heapIndexRecord[bh->elements[index]->vertexIndex] = index; //update the heapIndexRecord}// Attention, the index of the heap starts from 1
// return the index the element inserted into the binary heap
void insert(ElementType value, BinaryHeap bh, int* heapIndexRecord)
{int i;if(isFull(bh)){Error("failed insertion , for the BinaryHeap is full, from func insert!");return ;    }   if(!isEmpty(bh))for(i = ++bh->size; bh->elements[i/2]->distance > value->distance; i /= 2)                  {//copyElement(bh->elements[i/2], bh->elements[i]);       *bh->elements[i] = *bh->elements[i/2];heapIndexRecord[bh->elements[i]->vertexIndex] = i; //update the heapIndexRecord}elsei = ++bh->size;     *bh->elements[i] = *value;heapIndexRecord[bh->elements[i]->vertexIndex] = i; //update the heapIndexRecord
}BinaryHeap initBinaryHeap(int capacity)
{BinaryHeap bh;ElementType *temp;int i;bh = (BinaryHeap)malloc(sizeof(struct BinaryHeap));if(!bh) {Error("out of space, from func initBinaryHeap");        return NULL;}  bh->capacity = capacity;bh->size = 0;temp = (ElementType*)malloc(capacity * sizeof(Distance));if(!temp) {Error("out of space, from func initBinaryHeap");        return NULL;} bh->elements = temp;for(i=0; i < capacity; i++){temp[i] = (ElementType)malloc(sizeof(struct Distance));if(!temp[i]) {Error("out of space, from func initBinaryHeap");        return NULL;}       }return bh;
}// allocate the memory for storing index of  vertex in heap and let every element -1
int *makeEmptyArray(int size)
{int *array;int i;array = (int*)malloc(size * sizeof(int));if(!array){Error("out of space ,from func makeEmptyArray");return NULL;}       for(i=0; i<size; i++)array[i] = -1;return array;
} void printIndexOfVertexInHeap(int size, int *array)
{int i;for(i=0; i<size; i++)    printf("\tindexOfVertexInHeap[%d] = %d\n", i+1, array[i]);   
}int main()
{int data[] = {85, 80, 40, 30, 10, 70, 110}; // P141 int buildHeapData[] = {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130};BinaryHeap bh;  int size;int i;  int capacity;Distance tempDisStruct;int *indexOfVertexInHeap;printf("\n\t=== test for inserting the binary heap with {85, 80, 40, 30, 10, 70, 110} in turn ===\n");capacity = 14;bh = initBinaryHeap(capacity);size = 7;   tempDisStruct = makeEmptyDistance(); indexOfVertexInHeap = makeEmptyArray(size);for(i = 0; i < size; i++) {tempDisStruct->distance = data[i];tempDisStruct->vertexIndex = i;insert(tempDisStruct, bh, indexOfVertexInHeap);}   printBinaryHeap(bh);printIndexOfVertexInHeap(bh->size, indexOfVertexInHeap);printf("\n\t=== test for inserting the binary heap with element {100, 20, 90} in turn ===\n");tempDisStruct->distance = 100;tempDisStruct->vertexIndex = size;insert(tempDisStruct, bh, indexOfVertexInHeap); printBinaryHeap(bh);tempDisStruct->distance = 20;tempDisStruct->vertexIndex = size+1;insert(tempDisStruct, bh, indexOfVertexInHeap); printBinaryHeap(bh);tempDisStruct->distance = 90;tempDisStruct->vertexIndex = size+2;insert(tempDisStruct, bh, indexOfVertexInHeap); printBinaryHeap(bh);printIndexOfVertexInHeap(bh->size, indexOfVertexInHeap);printf("\n\t=== test for inserting the binary heap with 5 ===\n");  tempDisStruct->distance = 5;tempDisStruct->vertexIndex = size+3;insert(tempDisStruct, bh, indexOfVertexInHeap); printBinaryHeap(bh);printf("\n\t=== test for 3 deletings towards the minimum in binary heap ===\n");deleteMin(bh, indexOfVertexInHeap); printBinaryHeap(bh);deleteMin(bh, indexOfVertexInHeap);     printBinaryHeap(bh);deleteMin(bh, indexOfVertexInHeap); printBinaryHeap(bh);
}

3.3)printing results:
这里写图片描述
这里写图片描述
这里写图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/331884.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

cucumber测试_如何在Cucumber中进行后端测试

cucumber测试Cucumber是一种规范语言的执行框架。 它并不是要成为测试语言&#xff0c;而是用于创建测试自动化。 Cucumber最适合出现一些实际参与者互动并取得某种成果的情况。 当可以从用户的角度编写它时&#xff0c;它特别有用。 Given Sarah is a premium club member W…

linux mysql删除密码忘记了_linux下忘记mysql密码的几种找回方法(推荐)

今天我们主要是讲一下关于linux忘记mysql密码处理方法&#xff0c;下面提供了5种linux忘记mysql密码找回方法哦。方法一(先进入root权限)&#xff1a;# /etc/init.d/mysql stop# mysqld_safe --usermysql --skip-grant-tables --skip-networking &# mysql -u rootmysql>…

Dijkstra 算法——计算有权最短路径(边有权值)

【0】README 0.1&#xff09; 本文总结于 数据结构与算法分析&#xff0c; 源代码均为原创&#xff0c; 旨在理解 Dijkstra 的思想并用源代码加以实现&#xff1b; 0.2&#xff09;最短路径算法的基础知识&#xff0c;参见 http://blog.csdn.net/pacosonswjtu/article/detail…

spring使用自定义注解_用Spring组成自定义注释

spring使用自定义注解Java批注在2004年随Java 5一起引入&#xff0c;是一种将元数据添加到Java源代码中的方法。 如今&#xff0c;许多主要框架&#xff08;如Spring或Hibernate&#xff09;都严重依赖注释。 在本文中&#xff0c;我们将介绍一个非常有用的Spring功能&#xf…

打印结果和调试结果不一样(C语言)

【0】README 0.1&#xff09;本文旨在阐述 个人的debug经历&#xff0c;遇到的各种debug 奇葩问题&#xff0c; 说是奇葩&#xff0c;其实也是自己 不小心或者说是编程习惯不好&#xff1b; 【1】debug和running的运行结果不一致&#xff08;乍眼一看&#xff0c;你肯定醉了&a…

mysql add default_MySQL中create table DEFAULT 用法

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)][table_options] [select_statement]TEMPORARY&#xff1a;该关键字表示用create table新建的表为临时表&#xff0c;此表在当前会话结束后将自动消失。临时表主要被应用于存储过程中&#xff0c;…

jakarta ee_Jakarta EE贡献–入门

jakarta ee您是否有兴趣帮助Jakarta EE向前发展&#xff1f; 我也是。我想提供一些详细信息&#xff0c;以帮助有兴趣入门的人。 第1步&#xff1a; 开始捐款的第一步是签署Eclipse Foundation Committer and Contributor Agreement&#xff08;ECA&#xff09;&#xff1a; …

最小生成树基础

【0】README 0.1&#xff09; 本文总结于 数据结构与算法分析&#xff0c; 源代码均为原创&#xff0c; 旨在 review 最小生成树的基础知识&#xff1b; 0.2&#xff09;了解本文的内容是 分析 Prim算法&#xff08;普利姆算法&#xff09;和 Kruskal算法&#xff08;克鲁斯卡…

mysql dump gtid_mysqldump命令详解 Part 3- 备份全库

前面说了MySQL Linux平台和Windows平台的安装下面开始是MySQL的一些学习笔记前面我们说了如果构造数据这节开始说MySQL 的备份环境为MySQL 5.7.25在解释命令之前我们先弄清楚数据库中有哪些对象上一节我们建立了数据库并建立相关的对象数据库表存储过程函数触发器事件这节讲一些…

apache lucene_Apache Lucene中的并发查询执行

apache luceneApache Lucene是一个出色的并发纯Java搜索引擎&#xff0c;如果您愿意&#xff0c;它可以轻松地使服务器上的可用CPU或IO资源饱和。 “典型” Lucene应用程序的并发模型在搜索时每个查询一个线程&#xff0c;但是您是否知道Lucene也可以使用多个线程同时执行一个查…

最小生成树——Prim(普利姆)算法

【0】README 0.1&#xff09; 本文总结于 数据结构与算法分析&#xff0c; 源代码均为原创&#xff0c; 旨在 理解Prim算法的idea 并用 源代码加以实现&#xff1b; 0.2&#xff09;最小生成树的基础知识&#xff0c;参见 http://blog.csdn.net/pacosonswjtu/article/details…

mysql grant usage on_grant 权限 on 数据库对象 to 用户

grant 权限 on 数据库对象 to 用户一、grant 普通数据用户&#xff0c;查询、插入、更新、删除 数据库中所有表数据的权利。grant select on testdb.* to common_user’%’grant insert on testdb.* to common_user’%’grant update on testdb.* to common_user’%’grant del…

openjdk8 项目结构_OpenJDK织机和结构化并发

openjdk8 项目结构Project Loom是Hotspot Group赞助的项目之一&#xff0c;旨在向JAVA世界提供高吞吐量和轻量级的并发模型。 在撰写本文时&#xff0c;Loom项目仍在积极开发中&#xff0c;其API可能会更改。 为什么要织机&#xff1f; 每个新项目可能会出现的第一个问题是为什…

mysql连库串_数据库连接串整理 - osc_ac5z111b的个人空间 - OSCHINA - 中文开源技术交流社区...

常用JDBC驱动与连接字符串MySQLdriver&#xff1a;com.mysql.jdbc.Driverurl&#xff1a;jdbc:mysql://localhost:3306/mydbMySQL url格式&#xff1a;jdbc:mysql://[host:port]/[database][?参数名1][参数值1][&参数名2][参数值2]…参数名称参数说明缺省值最低版本要求us…

最小生成树——Kruskal(克鲁斯卡尔)算法

【0】README 0.1&#xff09; 本文总结于 数据结构与算法分析&#xff0c; 源代码均为原创&#xff0c; 旨在 理解 Kruskal&#xff08;克鲁斯卡尔&#xff09;算法 的idea 并用 源代码加以实现&#xff1b; 0.2&#xff09;最小生成树的基础知识&#xff0c;参见 http://blo…

java 正则表达式 开头_如何在Java中修复表达式的非法开头

java 正则表达式 开头您是否遇到过这个令人难以置信的错误&#xff0c;想知道如何解决它&#xff1f; 让我们仔细阅读一下&#xff0c;研究如何解决表达式Java非法开头错误。 这是一个动态错误&#xff0c;这意味着编译器会发现某些不符合Java编程规则或语法的内容。 初学者大…

php mysql数据备份命令_MySQL数据备份与恢复的相关操作命令

将mysql安装目录设置到系统环境变量中, 方便在命令行终端直接执行.linux下mysql安装后, root默认密码为空, 可直接执行mysql 登录将mysql安装目录设置到系统环境变量中, 方便在命令行终端直接执行.linux下mysql安装后, root默认密码为空, 可直接执行mysql 登录.正常登录命令mys…

DFS——深度优先搜索基础

【0】README 0.1&#xff09; 本文总结于 数据结构与算法分析&#xff0c; 源代码均为原创&#xff0c; 旨在 review DFS——深度优先搜索 的基础知识&#xff1b; 【1】深度优先搜索的应用 1.1&#xff09;深度优先搜索算法描述&#xff08;转自天勤计算机考研高分笔记——数…

rest post put_REST / HTTP方法:POST与PUT与PATCH

rest post put每个HTTP请求都包含一个方法 &#xff08;有时称为verb &#xff09;&#xff0c;该方法指示对标识的资源执行的操作。 在构建RESTful Web服务时&#xff0c;HTTP方法POST通常用于创建资源&#xff0c;而PUT用于资源更新。 尽管在大多数情况下这很好&#xff0c;…

回归模型的score得分为负_深度研究:回归模型评价指标R2_score

回归模型的性能的评价指标主要有&#xff1a;RMSE(平方根误差)、MAE(平均绝对误差)、MSE(平均平方误差)、R2_score。但是当量纲不同时&#xff0c;RMSE、MAE、MSE难以衡量模型效果好坏。这就需要用到R2_score&#xff0c;实际使用时&#xff0c;会遇到许多问题&#xff0c;今天…