1.实验目的
1)掌握图的存储结构及其基本操作,学会定义图的邻接表存储结构,并能在实际中灵活应用;
(2)掌握拓扑排序算法;
(3)通过本实验的具体应用实例,灵活应用拓扑排序并进一步巩固队列/栈的运用。
2.实验内容
用邻接表形式存储以下有向无环图,进行拓扑排序,输出相应拓扑序列。若图中每个顶点都在拓扑序列中,说明图中无环。
3.源程序和实验结果
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 20
#define MAXN 100
typedef struct
{
int *base, *top;
int stacksize;
}SqStack;
typedef struct ArcNode
{
int adjvex;
struct ArcNode *next;
}ArcNode;
typedef struct VNode
{
int data;
ArcNode *firstarc;
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct
{
AdjList vertices;
int vexnum, arcnum;
}ALGraph;
void AddEdge(ArcNode *p1, ArcNode *p2)
{
ArcNode *p = p1;
while(p->next)
p = p->next;
p->next = p2;
}
void CreateGraph(ALGraph *G, int in[])
{
int n, m, i;
scanf("%d%d", &n, &m);
G->vexnum = n;
G->arcnum = m;
for(i = 1; i <= n; i++)
{
G->vertices[i].data = i;
G->vertices[i].firstarc = NULL;
}
for(i = 1; i <= m; i++)
{
int st, ed;
scanf("%d%d", &st, &ed);
ArcNode *NewNode = (ArcNode *)malloc(sizeof(NewNode));
NewNode->adjvex = ed;
NewNode->next = NULL;
in[ed]++;
if(G->vertices[st].firstarc == NULL)
G->vertices[st].firstarc = NewNode;
else
AddEdge(G->vertices[st].firstarc, NewNode);
}
}
void TopologicalSort(ALGraph *G, int in[])
{
int i;
SqStack *s = (SqStack *)malloc(sizeof(SqStack));
InitStack(s);
for(i = 1; i <= G->vexnum; i++)
if(in[i] == 0)
Push(s, i);
int count = 0;
while(!Empty(s))
{
int temp = GetTop(s);
Pop(s);
printf("%d ", G->vertices[temp].data);
count++;
ArcNode *p;
for(p = G->vertices[temp].firstarc; p; p = p->next)
{
int k = p->adjvex;
if(!--in[k]) Push(s, k);
}
}
}
void InitStack(SqStack *S)
{
S->base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
}
void Push(SqStack *S, int e)
{
if(S->top - S->base >= S->stacksize)
{
S->base = (int *)realloc(S->base, (S->stacksize+STACKINCREMENT) * sizeof(int));
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top) = e;
S->top++;
}
int Pop(SqStack *S)
{
int e = GetTop(S);
S->top--;
return e;
}
int GetTop(SqStack *S)
{
return *(S->top-1);
}
int Empty(SqStack *S)
{
if(S->top == S->base) return 1;
else return 0;
}
int main()
{
//freopen("testdata.in", "r", stdin);
ALGraph *g = (ALGraph*)malloc(sizeof(ALGraph));
int indegree[MAX_VERTEX_NUM];
memset(indegree, 0, sizeof(indegree));
CreateGraph(g, indegree);
TopologicalSort(g, indegree);
system("pause");
return 0;
}