6-1 Is Topological Order (30 分)


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):

topord.JPG

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
 
結尾無空行
 
int p[10000];
bool IsTopSeq(LGraph Graph, Vertex Seq[])
{
    for (int i = 0; i < Graph->Nv; i++)
    {
        p[Seq[i] - 1] = i;
    }
    for (int i = 0; i < Graph->Nv; i++)
    {
        PtrToAdjVNode cur = Graph->G[i].FirstEdge;
        while (cur)
        {
            if (p[i] > p[cur->AdjV])
            {
                return false;
            }
            cur = cur->Next;
        }
    }
    return true;
}

拓撲序列的構成:

每次選取入度為0的節點,所以一個圖可以有不同的拓撲序列

判定拓撲序列只需判斷給出的序列中節點的位置是否與圖中的位置不符,

比如5 2 1 6 3 4這個序列,由於2排在了1的前面,所以不能構成拓撲序列

第一個for循環,將給出的序列按位置賦值,p[5]=0,p[2]=1.... p[4]=5

然后第二個for循環,通過訪問鄰接表的數據,如果p[i]>p[cur->Adjv],則說明存在一個結點,位置大於前面,此時不符合拓撲序列,則return false

如果走完全部序列都沒有發現問題,那么此序列為拓撲序列

然后此題目還有一個坑“Note: Although the vertices are numbered from 1 to MaxVertexNum, they are indexed from 0 in the LGraph structure.”

所以p[Seq[i] - 1] = i,賦值的時候需要減1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM