算法导论 单源最短路径 Dijkstra

#include 
#include 
#include 
#include "FIB.h"

//图节点
typedef struct VertexNode
{
	char name;
	int key;
	VertexNode *p;
	pFNode pf;
}Vertex,*pVertex;

//图
typedef struct 
{
	int vn;
	int **E;
	pVertex *V;
	
}Graph,*pGraph;
//根据算法导论 图24-6 初始化图
pGraph initGraph()
{
	pGraph g=(pGraph)malloc(sizeof(Graph));
	g->vn=5;
	pVertex vs=(pVertex)malloc(sizeof(Vertex));
	vs->name='s';
	vs->key=0;
	vs->p=NULL;
	pVertex vt=(pVertex)malloc(sizeof(Vertex));
	vt->name='t';
	vt->key=INT_MAX;
	vt->p=NULL;
	pVertex vy=(pVertex)malloc(sizeof(Vertex));
	vy->name='y';
	vy->key=INT_MAX;
	vy->p=NULL;
	pVertex vx=(pVertex)malloc(sizeof(Vertex));
	vx->name='x';
	vx->key=INT_MAX;
	vx->p=NULL;
	pVertex vz=(pVertex)malloc(sizeof(Vertex));
	vz->name='z';
	vz->key=INT_MAX;
	vz->p=NULL;

	g->V=(pVertex*)malloc(g->vn*sizeof(pVertex));
	g->V[0]=vs;
	g->V[1]=vt;
	g->V[2]=vx;
	g->V[3]=vy;
	g->V[4]=vz;

	g->E = (int**)malloc(g->vn*sizeof(int*));
	for(int i=0;ivn;i++)
	{
		g->E[i]=(int*)malloc(g->vn*sizeof(int));
	}
	for(int i=0;ivn;i++)
	{
		for(int j=0;jvn;j++)
		{
			g->E[i][j]=INT_MAX;
		}
	}
	g->E[0][1]=20;
	g->E[0][2]=5;
	g->E[1][2]=2;
	g->E[1][3]=1;
	g->E[2][1]=3;
	g->E[2][3]=9;
	g->E[2][4]=2;
	g->E[3][4]=4;
	g->E[4][3]=6;
	g->E[4][0]=7;
	return g;
}

void relax(pGraph g,int u,int v,pFIB h)
{
	//无边,不进行松弛
	if(g->E[u][v]==INT_MAX)
		return;
	int sum,uk=g->V[u]->key,vk=g->V[v]->key,ew=g->E[u][v];
	//根据规则,加上无穷等于无穷
	if(uk==INT_MAX || ew==INT_MAX)
		sum=INT_MAX;
	else
		sum=uk+ew;
	if(vk>sum)
	{
		g->V[v]->key=sum;
		g->V[v]->p=g->V[u];
		FIB_heap_decreaseKey(h,g->V[v]->pf,sum);
	}
}

void printKey(pGraph g)
{
	for(int i=0;ivn;i++)
	{
		printf("%c %d\n",g->V[i]->name,g->V[i]->key);
	}
}

void main()
{
	pGraph g=initGraph();
	pFIB h=make_FIB_heap();
	for(int i=0;ivn;i++)
	{
		pFNode pf=createNode(g->V[i]->key);
		g->V[i]->pf=pf;
		pf->vi=i;
		FIB_heap_insert(h,pf);
	}
	while(h->n>0)
	{
		pFNode uf=FIB_heap_extract_min(h);
		int u=uf->vi;
		for(int v=0;vvn;v++)
		{
			if(g->E[u][v]

你可能感兴趣的:(算法导论)