PAT (Advanced Level) Practice 1146 Topological Order (25分) (拓扑序列的判断)

1.题目

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.

gre.jpg

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

2.题目分析

1.拓扑序列的判断:拓扑序列,即有向无环,每次找一个入度为零的点,将所有和它相连的点的入度减一(删除相连的边),重复此步骤(有n个点,每次选择一个入度为0的点,进行n次)。如果这时还有入度不为零的点,证明有环。

2.注意要是进行多次判断的话,记得不能动原来的in数组,要另外设置备份数组进行修改判断

3.代码

#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
#define MAX 1050
int n, m,k;
int edges[MAX][MAX];
int in[MAX];
int main()
{
	scanf("%d %d", &n, &m);
	int a, b;
	for (int i = 1; i <= m; i++)
	{
		scanf("%d %d", &a, &b);
		edges[a][b] = 1;
		in[b]++;
	}
	scanf("%d", &k);
	int space = 0;
	for (int i = 1; i <= k; i++)
	{
        bool ok=true;
		vector<int>temp(in, in + n + 1);
		for (int j = 1; j <= n; j++)
		{
			int c;
			scanf("%d", &c);
			if (temp[c] != 0)
			ok=false;
			for (int s = 1; s <= n; s++)
				if (edges[c][s] != 0)
                temp[s]--;
		}
            if(!ok)
            {
				if (space == 0) { printf("%d", i - 1); space++; }
				else printf(" %d", i - 1);
			}
	}
}

 

posted @ 2020-03-21 19:10  Jason66661010  阅读(80)  评论(0编辑  收藏  举报