PAT Advanced 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.

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

题目分析

已知有向无环图,顶点和边,判断一系列序列是否是拓扑序列
拓扑序列:

  • 每次从图中取一个入度为0的顶点,并将该顶点指向的顶点的入度减1
  • 继续取出入度为0的顶点,循环一直到图中所有顶点被取出

解题思路

  1. 适合用邻接表存储有向图(访问边遍历复杂度低),并记录每个顶点的入度
  2. 判断是否为拓扑排序
    2.1 依次输入拓扑序列的顶点,判断入度是否为0
    若入度不为0,isTop=false,即不是拓扑序列
    若入度为0,将当前节点指向的顶点的入度-1
    2.2 依次循环执行,直到序列中所有顶点被校验

易错点

  1. 在解题思路2.1中判断入度不为0,不能直接break,因为要将序列接收完
  2. 每次新输入一个序列时,需要重新拷贝一份图各个顶点的入度信息,重新计算

Code

#include <iostream>
#include <vector>
using namespace std;
int main(int argc,char * argv[]) {
	int n,m,a,b,k,v,flag=0;
	scanf("%d %d",&n,&m);
	vector<int> edge[n+1];
	int indegree[n+1]= {0};
	for(int i=0; i<m; i++) {
		scanf("%d %d",&a,&b);
		edge[a].push_back(b);
		indegree[b]++;
	}
	scanf("%d",&k);
	for(int i=0; i<k; i++) {
		int isTop = 1;
		vector<int> cindegree(indegree, indegree+n+1);
		for(int j=1; j<=n; j++) {
			scanf("%d",&v);
			if(cindegree[v]!=0) isTop=0;
			for(int r=0; r<edge[v].size(); r++) {
				--cindegree[edge[v][r]];
			}
		}
		if(isTop==0) {
			printf("%s%d",flag==1?" ":"",i);
			flag=1;
		}
	}
	return 0;
}

原文地址:https://www.cnblogs.com/houzm/p/12391372.html