欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[Python](PAT)1146 Topological Order(25 分)

程序员文章站 2022-03-13 13:40:53
...

点这里,用Python写PAT甲级的答案都有

1146 Topological Order(25 分)

This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topological order obtained from the given directed graph? Now you are supposed to write a program to test each of the options.

[Python](PAT)1146 Topological Order(25 分)

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (≤ 1,000), the number of vertices in the graph, and M (≤ 10,000), the number of directed edges. Then M lines follow, each gives the start and the end vertices of an edge. The vertices are numbered from 1 to N. After the graph, there is another positive integer K (≤ 100). Then K lines of query follow, each gives a permutation of all the vertices. All the numbers in a line are separated by a space.

Output Specification:

Print in a line all the indices of queries which correspond to "NOT a topological order". The indices start from zero. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line. It is graranteed that there is at least one answer.

Sample Input:

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:

3 4

题目大意

给定一个有向图,再给定若干个查询,每个查询中包括一个有向拓扑序列。如果这个查询中的有向拓扑序列不是这个有向图的有向拓扑序列,则输出该查询的编号。

分析

关于邮箱拓扑图的介绍,可以看这里有向拓扑图

使用start字典来记录每个节点的向下连接点。

使用to字典记录每个节点的入度。

遍历每一个查询,遍历查询中的序列中的每一个元素。

如果当前元素的入度不为0,则说明这个点还有前驱点,不应该弹出。所以把这个查询的编号压入result数组。

否则的话,把这个应该弹出的节点对应的各个向下连接点的入度减一。

最终输出所有的非有向拓扑图查询编号即可

Python实现

def main():
    line = input().split(" ")
    n,m = int(line[0]), int(line[1])
    start = {key : [] for key in range(n)}
    to = {key : 0 for key in range(n)}
    for x in range(m):
        line = input().split(" ")
        a, b = int(line[0])-1, int(line[1])-1
        start[a].append(b)
        to[b] += 1
    k = int(input())
    result = []
    for x in range(k):
        line = input().split(" ")
        num = [int(x)-1 for x in line]
        t = start.copy()
        h = to.copy()
        for i in num:
            if h[i] !=0:
                result.append(x)
                break
            else:
                for j in t[i]:
                    h[j] -= 1
    print(*result)

if __name__ == "__main__":
    main()

 更多技术干货,有趣文章,点这里没错