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
6
5 2 3 6 4 1
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:
0 4 5
所谓拓扑顺序就是做事顺序,也就是做到下一个节点时必须经过上一个节点
解题思路:第一种方法,记录每个节点度数,根据给定的序列判断是否是拓扑顺序
第二种方法
首先,先将给定的集合按照给定顺序存入下标p
其次,遍历整张图,判断每个有向边的两个节点 a,b 的在p中的位置
最后,如果发现p[a] > p[b] 就不是拓扑排序
无需出度和入度的方法
第一种
#include<iostream>
#include<vector>
using namespace std;
const int N = 10100;
int n,m;
vector<int>gra[N];
vector<int>pan_cnt_front(N);//统计出现的次数
bool pan_is_toporder(vector<int>&exam)
{
vector<int>pan_cnt_front_copy = pan_cnt_front;
int len = exam.size();
for(int i:exam)
{
if(pan_cnt_front_copy[i]) return false;
for(int j:gra[i]) pan_cnt_front_copy[j]--;
}
return true;
}
int main()
{//拓扑顺序 做事顺序做到下一个节点时必须经过上一个节点
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++)
{
int num1,num2;
cin>>num1>>num2;
gra[num1].push_back(num2);//有向图
pan_cnt_front[num2]++;
}
int k;
cin>>k;
vector<int>res;
for(int j=0;j<k;j++)
{
vector<int>exam(n);
for(int i=0;i<n;i++)
scanf("%d",&exam[i]);
if(!pan_is_toporder(exam)) res.push_back(j);
}
for(int i=0;i<res.size();i++)
{
if(i!=0) cout<<" ";
cout<<res[i];
}
}
第二种
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1010 , M = 1e4 + 10;
int n , m;
int p[N];
struct edge
{
int a , b;
}w[M];
int main()
{
cin >> n >> m;
for(int i = 0;i < m;i ++) cin >> w[i].a >> w[i].b;
int k;
cin >> k;
vector<int>v;
for(int i = 0;i < k;i ++)
{
for(int j = 1;j <= n;j ++)
{
int x;
cin >> x;
p[x] = j;
}
bool flag = true;
for(int j = 0;j < m;j ++)
{
if(p[w[j].a] > p[w[j].b])
{
flag = false;
break;
}
}
if(!flag) v.push_back(i);
}
for(int i = 0;i < v.size();i ++)
{
if(i) cout << ' ';
cout << v[i];
}
return 0;
}