Write a program to find the topological order in a digraph.(编写一个程序来查找有向图中的拓扑顺序。)
函数接口定义:
bool TopSort( LGraph Graph, Vertex TopOrder[] );
where LGraph is defined as the following:
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
The topological order is supposed to be stored in TopOrder[] where TopOrder[i] is the i-th vertex in the resulting sequence. The topological sort cannot be successful if there is a cycle in the graph – in that case TopSort must return false; otherwise return true.(拓扑顺序应该存储在TopOrder[]中,其中TopOrder[i]是结果序列中的第i个顶点。如果图中有一个循环,拓扑排序就不可能成功——在这种情况下,TopSort必须返回false;否则返回true。)
Notice that the topological order might not be unique, but the judge’s input guarantees the uniqueness of the result.(请注意,拓扑顺序可能不是唯一的,但官方的输入保证了结果的唯一性。)
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10 /* maximum number of vertices */
typedef int Vertex; /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph ReadG(); /* details omitted */
bool TopSort( LGraph Graph, Vertex TopOrder[] );
int main()
{
int i;
Vertex TopOrder[MaxVertexNum];
LGraph G = ReadG();
if ( TopSort(G, TopOrder)==true )
for ( i=0; i<G->Nv; i++ )
printf("%d ", TopOrder[i]);
else
printf("ERROR");
printf("\n");
return 0;
}
/* Your function will be put here */
输入样例1:
5 7
1 0
4 3
2 1
2 0
3 2
4 1
4 2
输出样例1:
4 3 2 1 0
输入样例2:
5 8
0 3
1 0
4 3
2 1
2 0
3 2
4 1
4 2
输出样例2:
ERROR
代码:
/*
1.先得到图中所有点的入度数,存进Indegree[]数组中
2.判断遍历到该点时的入度是否为零,不为零则返回false
3.入度为零,则存进TopOrder[]里,然后遍历该点的所有邻接点,减去邻接边,则入度数-1
4.如果最后TopOrder里存入的顶点个数!=图的顶点个数,则返回false,反之返回true
*/
bool TopSort( LGraph Graph, Vertex TopOrder[] )//邻接表
{
int Indegree[MaxVertexNum],cnt=0;
Vertex v;
PtrToAdjVNode p;
int queue[MaxVertexNum];
int front=0,rear=0;
//初始化Indegree[]
for(v=0;v<Graph->Nv;v++)
Indegree[v]=0;
//遍历图得到图的入度数Indegree[]
for(v=0;v<Graph->Nv;v++)
{
for(p=Graph->G[v].FirstEdge;p;p=p->Next)
Indegree[p->AdjV]++;
}
//将所有入度为0的顶点放进数组queue[]
for(v=0;v<Graph->Nv;v++)
if(Indegree[v]==0) queue[rear++]=v;
while(front!=rear)
{
//取出入度为零的顶点v
v=queue[front++];
//存进TopOrder数组中
TopOrder[cnt++]=v;
//对v的每个邻接点都循环一遍,删除与v相连的边
for(p=Graph->G[v].FirstEdge;p;p=p->Next)
if(--Indegree[p->AdjV]==0) queue[rear++]=p->AdjV;
}
if(cnt!=Graph->Nv) return false;
else return true;
}