Write a program to test if a give sequence Seq
is a topological order of a given graph Graph
.
Format of functions:
bool IsTopSeq( LGraph Graph, Vertex Seq[] );
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 function IsTopSeq
must return true
if Seq
does correspond to a topological order; otherwise return false
.
Note: Although the vertices are numbered from 1 to MaxVertexNum, they are indexed from 0 in the LGraph structure.
Sample program of judge:
#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 1 to MaxVertexNum */ 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 IsTopSeq( LGraph Graph, Vertex Seq[] ); int main() { int i, j, N; Vertex Seq[MaxVertexNum]; LGraph G = ReadG(); scanf("%d", &N); for (i=0; i<N; i++) { for (j=0; j<G->Nv; j++) scanf("%d", &Seq[j]); if ( IsTopSeq(G, Seq)==true ) printf("yes\n"); else printf("no\n"); } return 0; } /* Your function will be put here */
Sample Input (for the graph shown in the figure):
6 8 1 2 1 3 5 2 5 4 2 3 2 6 3 4 6 4 5 1 5 2 3 6 4 5 1 2 6 3 4 5 1 2 3 6 4 5 2 1 6 3 4 1 2 3 4 5 6
Sample Output:
yes yes yes no no
题目的大致意思就是,给你一组数据,根据这组数据构建一个有向图,再给你几组序列,判断是不是拓扑序列。
思路:先确定每个结点的入度数,按拓扑顺序输出结点时,每输出一个结点,将其子结点的入度数 -1.
注意:输入的顶点是从 0 开始存放的,也就是
0 | 1 | 2 | 3 | 4 |
G1 | G2 | G3 | G4 | G5 |
struct AdjVNode{ Vertex AdjV; PtrToAdjVNode Next; };
中的 AdjV,也是从 0 开始存放。
代码:
bool IsTopSeq( LGraph Graph, Vertex Seq[] ){
int inDegree[1000]; for(int i=0;i<=Graph->Nv;i++) inDegree[i]=0;
PtrToAdjVNode temnode; for(int i=0;i<Graph->Nv;i++){ temnode=Graph->G[i].FirstEdge; while (temnode){ inDegree[temnode->AdjV]++; temnode=temnode->Next; } }
for(int i=0;i<Graph->Nv;i++){ if(inDegree[Seq[i]-1]!=0) return false; else{ temnode=Graph->G[Seq[i]-1].FirstEdge; while(temnode){ inDegree[temnode->AdjV]--; temnode=temnode->Next; } } } return true; }