PTA Topological Sort

生病了好蓝过啊,哎还是家里好,生病都不能码代码了TAT……

下面是题目:

Write a program to find the topological order in a digraph.

Format of functions:

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 returnfalse; otherwise return true.

Notice that the topological order might not be unique, but the judge‘s input guarantees the uniqueness of the result.

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 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 */

Sample Input 1 (for the graph shown in the figure):

5 7
1 0
4 3
2 1
2 0
3 2
4 1
4 2

Sample Output 1:

4 3 2 1 0

Sample Input 2 (for the graph shown in the figure):

5 8
0 3
1 0
4 3
2 1
2 0
3 2
4 1
4 2

Sample Output 2:

ERROR

解答:

这道题目蛮基础的……就是把拓扑排序实现一遍,先遍历整个图计算所有节点的入度并存入数组inorder中,然后进行一个循环,循环每次找到任意一个入度为0的点加入拓扑排序的那个数组中,再将所有从该节点出发的边删除。当然这里在寻找入度为0的节点的时候可以用队列进行一个优化(毕竟每次找入度为0的节点都要遍历inorder数组太费时了),不然第三个测试点会超时(本宝宝还专门试了一下),就是一开始先遍历一遍inorder将入度为0的点入队,然后之后每次删除边的时候都判断一下是否会产生入度为0的点,如果是的话就将它入队,而每次取入度为0的节点加入拓扑排序的数组中的时候就只要取队首节点就可以了,相当于出队操作。这样优化后判断是否有环就可以这样进行:如果在将所有节点加入拓扑排序之前队列就为空了,那么就表示该图有环。

//
//  main.c
//  Topological Sort
//
//  Created by 余南龙 on 2016/11/16.
//  Copyright ? 2016年 余南龙. All rights reserved.
//

bool TopSort( LGraph Graph, Vertex TopOrder[] ){
    int indegree[Graph->Nv];
    int Q[MaxVertexNum];
    int i, head = -1, tail = 0, j = 0;
    PtrToAdjVNode tmp;

    for(i = 0; i < Graph->Nv; i++){
        indegree[i] = 0;
    }
    for(i = 0; i < Graph->Nv; i++){
        tmp = (Graph->G[i]).FirstEdge;
        while(NULL != tmp){
            indegree[tmp->AdjV]++;
            tmp = tmp->Next;
        }
    }
    for(i = 0; i < Graph->Nv; i++){
        if(0 == indegree[i]){
            Q[tail] = i;
            tail++;
        }
    }
    for(i = 0; i < Graph->Nv; i++){
        if(0 == tail){
            return false;
        }
        if(head == tail - 1){
            return false;
        }

        TopOrder[j++] = Q[++head];
        tmp = (Graph->G[Q[head]]).FirstEdge;
        while(NULL != tmp){
            indegree[tmp->AdjV]--;
            if(0 == indegree[tmp->AdjV]){
                Q[tail] = tmp->AdjV;
                tail++;
            }
            tmp = tmp->Next;
        }
    }

    return true;
}
时间: 2024-08-11 01:34:58

PTA Topological Sort的相关文章

Some facts about topological sort

Definition: a topological sort of a DAG G is a sort such that for all edge (i,j) in G, i precedes j. Then we have following corollaries: A sort is a topological sort of a DAG G iff for all i, j such that there is a path from i to j, i precedes j in t

Topological Sort

In what kind of situation will we need to use topological sort? Precedence(优先级) scheduling, say given a set of tasks to be completed with precedence constraints, in which order should we schedule the tasks? One simple example are classes in universit

拓扑排序(Topological Sort)

Graph 拓扑排序(Topological Sort) 假设一个应用场景:你用 C 编写了一个爬虫工具,其中有很多自定义的库:queue.c.queue.h.stack.c.stack.h.heap.c.heap.h 等等,且这些文件没有其他自定义库的依赖:另外还有一些基于上述自定义库的库:bfs.c.bfs.h.dfs.c.dfs.h.dijkstra.c.dijkstra.h.tcpSocket.c.tcpSocket.h 等等:基于以上的库,你开发了一些爬虫程序 scrawlYoutub

&lt;算法基础&gt;图的三种遍历方法————DFS,BFS,Topological sort

1.BFS(Breadth First Search) 具体实现的时候用栈来实现更简单.从start point开始,一圈圈向外. 对于例图的访问顺序是——s,a,c,d,e,b,g,f 2.DFS(Depth First Search) DFS(s){ 首先访问定点s: if(s尚有未被访问的邻居){任取其一u,递归执行DFS(u);}else{return;} } 对于例图的访问顺序是——s,a,e,f,g,b,c,d 3.Topological Sort 仅仅用于有向无环图. 从AOV网中

Topological Sort (25分)

Write a program to find the topological order in a digraph. Format of functions: bool TopSort( LGraph Graph, Vertex TopOrder[] ); where LGraph is defined as the following: typedef struct AdjVNode *PtrToAdjVNode; struct AdjVNode{ Vertex AdjV; PtrToAdj

Leetcode: Alien Dictionary &amp;&amp; Summary: Topological Sort

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the

LeetCode编程训练 - 拓扑排序(Topological Sort)

拓扑排序基础 拓扑排序用于解决有向无环图(DAG,Directed Acyclic Graph)按依赖关系排线性序列问题,直白地说解决这样的问题:有一组数据,其中一些数据依赖其他,问能否按依赖关系排序(被依赖的排在前面),或给出排序结果. 最常用解决拓扑排序问题的方法是Kahn算法,步骤可以概括为: 1. 根据依赖关系,构建邻接矩阵或邻接表.入度数组 2. 取入度为0的数据(即不依赖其他数据的数据),根据邻接矩阵/邻接表依次减小依赖其的数据的入度 3. 判断减小后是否有新的入度为0的数据,继续进

Hdoj 5195 DZY Loves Topological Sorting 【拓扑】+【线段树】

DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 922 Accepted Submission(s): 269 Problem Description A topological sort or topological ordering of a directed graph i

hdu 5195 DZY Loves Topological Sorting 线段树+拓扑排序

DZY Loves Topological Sorting Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5195 Description A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for ev