最小生成樹(隣接表の表記)
3878 ワード
#include
#include
#define max 20
typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
int info;
} ArcNode;
typedef struct VertexNode
{
char data;
ArcNode *firstarc;
}VertexNode;
typedef struct{
VertexNode vertex[max];
int vexnum,arcnum;
}AdjList;
AdjList *G=(AdjList *)malloc(sizeof(AdjList));
AdjList *primtree=(AdjList *)malloc(sizeof(AdjList));
int locatevertex(AdjList *G,char x)
{
for(int i=0;ivexnum;i++)
{
if(G->vertex[i].data==x)
return i;
}
return -1;
}
int creategraph(AdjList *G) /* */
{
int i,j,k,power;
char v1,v2;
printf(" :
");
scanf("%d%d",&G->vexnum,&G->arcnum);
fflush(stdin);
printf(" :
");
for(i=0;ivexnum;i++)
{
fflush(stdin);
scanf("%c",&G->vertex[i].data);
G->vertex[i].firstarc=NULL;
}
printf(" :
");
for(i=0;iarcnum;i++)
{
fflush(stdin);
scanf("%c %c%d",&v1,&v2,&power);
j=locatevertex(G,v1);
k=locatevertex(G,v2);
ArcNode *arc=(ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex=k;
arc->info=power;
arc->nextarc=G->vertex[j].firstarc;
G->vertex[j].firstarc=arc;
arc=(ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex=j;
arc->info=power;
arc->nextarc=G->vertex[k].firstarc;
G->vertex[k].firstarc=arc;
}
}
void initprimtree(AdjList *G,AdjList *primtree) /* */
{
int i;
for(i=0;ivexnum;i++)
{
primtree->vertex[i].data=G->vertex[i].data;
primtree->vertex[i].firstarc=NULL;
}
primtree->vexnum=G->vexnum;
}
ArcNode *makenode(int adjvex,int power) /* */
{
ArcNode *newnode=(ArcNode *)malloc(sizeof(ArcNode));
newnode->nextarc=NULL;
newnode->adjvex=adjvex;
newnode->info=power;
return newnode;
}
void createprimtree(AdjList *G,AdjList *primtree) /* */
{
int visit[G->vexnum]; /*visit */
int i,j,k;
int power,adjvex;
ArcNode *temp=(ArcNode *)malloc(sizeof(ArcNode));
for(i=0;ivexnum;i++) /*visit 0, */
visit[i]=0;
visit[0]=1; /* */
for(i=0;ivexnum;i++)
{
power=999;
for(j=0;jvexnum;j++)
{
if(visit[j]) /* , */
{
temp=G->vertex[j].firstarc;
while(temp!=NULL)
{
if(power>temp->info&&!visit[temp->adjvex]) /* */
{
power=temp->info;
adjvex=temp->adjvex;
k=j; /* */
}
temp=temp->nextarc;
}
}
}
if(!visit[adjvex])
{
if(primtree->vertex[k].firstarc==NULL)
primtree->vertex[k].firstarc=makenode(adjvex,power); /* */
else
{
temp=primtree->vertex[k].firstarc;
while(temp->nextarc!=NULL)
temp=temp->nextarc;
temp->nextarc=makenode(adjvex,power);
}
visit[adjvex]=1;
}
}
}
void print(AdjList *primtree) /* */
{
ArcNode *p;
p=(ArcNode *)malloc(sizeof(ArcNode));
int i;
for(i=0;ivexnum;i++)
{
p=primtree->vertex[i].firstarc;
while(p)
{
printf("%c—%c(%d)
",primtree->vertex[i].data,primtree->vertex[p->adjvex].data,p->info);
p=p->nextarc;
}
}
}
int main()
{
creategraph(G); /* */
initprimtree(G,primtree); /* */
createprimtree(G,primtree); /* */
printf(" :
");
print(primtree); /* */
return 0;
}