#include <stdio.h>
#include <stdlib.h>
#include "FIB.h"
#include <limits.h>
//图节点
typedef struct VertexNode
{
char name;
int key;
VertexNode *p;
pFNode fn;
}Vertex,*pVertex;
//图
typedef struct
{
int vn;
int en;
int **E;
pVertex *V;
}Graph,*pGraph;
//根据算法导论 图23-4 初始化图
pGraph initGraph()
{
pGraph g=(pGraph)malloc(sizeof(Graph));
g->vn=9;
g->en=14;
pVertex va=(pVertex)malloc(sizeof(Vertex));
va->name='a';
va->key=0;
va->p=NULL;
pVertex vb=(pVertex)malloc(sizeof(Vertex));
vb->name='b';
vb->key=INT_MAX;
vb->p=NULL;
pVertex vc=(pVertex)malloc(sizeof(Vertex));
vc->name='c';
vc->key=INT_MAX;
vc->p=NULL;
pVertex vd=(pVertex)malloc(sizeof(Vertex));
vd->name='d';
vd->key=INT_MAX;
vd->p=NULL;
pVertex ve=(pVertex)malloc(sizeof(Vertex));
ve->name='e';
ve->key=INT_MAX;
ve->p=NULL;
pVertex vf=(pVertex)malloc(sizeof(Vertex));
vf->name='f';
vf->key=INT_MAX;
vf->p=NULL;
pVertex vg=(pVertex)malloc(sizeof(Vertex));
vg->name='g';
vg->key=INT_MAX;
vg->p=NULL;
pVertex vh=(pVertex)malloc(sizeof(Vertex));
vh->name='h';
vh->key=INT_MAX;
vh->p=NULL;
pVertex vi=(pVertex)malloc(sizeof(Vertex));
vi->name='i';
vi->key=INT_MAX;
vi->p=NULL;
g->V=(pVertex*)malloc(g->vn*sizeof(pVertex));
g->V[0]=va;
g->V[1]=vb;
g->V[2]=vc;
g->V[3]=vd;
g->V[4]=ve;
g->V[5]=vf;
g->V[6]=vg;
g->V[7]=vh;
g->V[8]=vi;
g->E = (int**)malloc(g->vn*sizeof(int*));
for(int i=0;i<g->vn;i++)
{
g->E[i]=(int*)malloc(g->vn*sizeof(int));
}
for(int i=0;i<g->vn;i++)
{
for(int j=0;j<g->vn;j++)
{
g->E[i][j]=0;
}
}
g->E[0][1]=g->E[1][0]=4;
g->E[1][2]=g->E[2][1]=8;
g->E[2][3]=g->E[3][2]=7;
g->E[3][4]=g->E[4][3]=9;
g->E[4][5]=g->E[5][4]=10;
g->E[5][6]=g->E[6][5]=2;
g->E[6][7]=g->E[7][6]=1;
g->E[0][7]=g->E[7][0]=8;
g->E[2][5]=g->E[5][2]=4;
g->E[3][5]=g->E[5][3]=14;
g->E[6][8]=g->E[8][6]=6;
g->E[7][8]=g->E[8][7]=7;
g->E[2][8]=g->E[8][2]=2;
g->E[1][7]=g->E[7][1]=11;
return g;
}
void printList(pVertex x)
{
while(x!=NULL)
{
printf("%c ",x->name);
x=x->p;
}
}
void printMST(pGraph g)
{
for(int i=0;i<g->vn;i++)
{
if(g->V[i]->p)
printf("%c,%c\n",g->V[i]->name,g->V[i]->p->name);
}
}
void main()
{
pVertex x=NULL;
pGraph g=initGraph();
pFIB fib=make_FIB_heap();
for(int i=0;i<g->vn;i++)
{
int k=g->V[i]->key;
pFNode fn=createNode(k);
fn->vi=i;
g->V[i]->fn=fn;
FIB_heap_insert(fib,fn);
}
//int lastMin=-1;
while(fib->n != 0)
{
pFNode fn=FIB_heap_extract_min(fib);
int u=fn->vi;
/*if(lastMin>=0)
g->V[u]->p=g->V[lastMin];
lastMin=u;*/
for(int i=0;i<g->vn;i++)
{
int w=g->E[u][i];
if(w>0)
{
pFNode t=g->V[i]->fn;
if(!t->deleted && w<g->V[i]->key)
{
g->V[i]->p=g->V[u];
g->V[i]->key=w;
FIB_heap_decreaseKey(fib,t,w);
}
}
}
if(fib->n==0)
x=g->V[u];
}
//printList(x);
printMST(g);
getchar();
}