//=======================================================================
//Use Adjacency List Implement Toplogical Sort
//BY:CHLAWS
//TIME:08-8-6
//PS:transshipment don't delete this headmark
//=======================================================================
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
int visited[MAX_VERTEX_NUM];
typedef char VertexType;
typedef struct ArcNode{
int adjvex; //该弧指向的顶点位置
struct ArcNode *nextarc; //指向下一个表(边)结点
int info; //权值
}ArcNode; //边结点类型
typedef struct VNode{
VertexType data;
int indegree;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices; //邻接表
int vexnum,arcnum; //顶点数和弧(边)数
}ALGraph;
int LocateVex(ALGraph G,char u);
void CreateALGraph_adjlist(ALGraph &G);
bool Toplogical_Sort(ALGraph G);
void main()
{
ALGraph G;
printf("This is Topological sort program!/n");
CreateALGraph_adjlist(G);
if(Toplogical_Sort(G))
{
printf("This digraph is not have cyncle!/n");
}
else
{
printf("This digraph is have cyncle!/n");
printf("So this erro!/n");
}
}
/**
**使用top 和G[].indegree构造一个栈
**使用top标记配合入度为0的点,将入度位置保存前一个入度为0的点
**出栈一次top回退一次
**/
bool Toplogical_Sort(ALGraph G)
{
int top = -1; //初始化标记栈空时,top位置为-1;
int count = 0;
ArcNode *pArc;
for (int ix=0; ix<G.vexnum; ++ix)
{
if(G.vertices[ix].indegree == 0)
{ //入栈
G.vertices[ix].indegree = top;
top = ix;
}
}
printf("/nIn the follow line is topological list:/n");
while(top+1)
{ //出栈
int ix = top;
top = G.vertices[top].indegree;
printf("%c ",G.vertices[ix].data);
count++;
for (pArc=G.vertices[ix].firstarc; pArc; pArc = pArc->nextarc)
{
int prev = pArc->adjvex;
G.vertices[prev].indegree--;
if(G.vertices[prev].indegree == 0)
{ //入栈
G.vertices[prev].indegree = top;
top = prev;
}
}
}
return count<G.vexnum ? false : true;
}
//查找符合的数据在数组中的下标
int LocateVex(ALGraph G,char u)
{
int i;
for (i=0;i<G.vexnum;i++)
{
if(u==G.vertices[i].data)
return i;
}
if (i==G.vexnum)
{
printf("Error u!/n");
exit(1);
}
return 0;
}
void CreateALGraph_adjlist(ALGraph &G)
{
int i,j,k,w; char v1,v2;
ArcNode *p;
printf("Input vexnum & arcnum:/n");
scanf("%d,%d",&G.vexnum,&G.arcnum);
printf("Input Vertices!/n");
for (i=0;i<G.vexnum;i++)
{
printf("Input %dth vertex:/n",i);
fflush(stdin);
scanf("%c",&G.vertices[i].data);
G.vertices[i].firstarc = NULL;
G.vertices[i].indegree = 0;
}
for (k=0;k<G.arcnum;k++)
{
printf("Input Arcs(v1,v2,w):/n");
fflush(stdin);
scanf("%c,%c,%d",&v1,&v2,&w);
i=LocateVex(G,v1);
j=LocateVex(G,v2);
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=j;
p->info = w;
p->nextarc=G.vertices[i].firstarc;
G.vertices[i].firstarc=p;
G.vertices[j].indegree++; //vi->vj vj入度+1
} return;
}