思路:
- 拓扑排序:在有向图中,若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面。
- 对于每个询问序列,先存储每个节点在序列中的下标,建立一个下标数组
- 再遍历每条边,判断起点下标是否比终点下标小(即判断起点是否在终点前面)
- 只用枚举边而不用遍历图,故用最简便的结构体来存储每条边
通过代码:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010, M = 10010;
int n, m;
struct Edge
{
int a, b;
}e[M];
int p[N];
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i ++ ) cin >> e[i].a >> e[i].b;
int k;
cin >> k;
bool is_first = true;
for (int i = 0; i < k; i ++ )
{
for (int j = 1; j <= n; j ++ )
{
int x;
cin >> x;
p[x] = j; //记录点的下标
}
bool success = true;
for (int j = 0; j < m; j ++ ) //遍历每一条边
if (p[e[j].a] > p[e[j].b])
{
success = false;
break;
}
if (!success)
{
if (is_first) is_first = false;
else cout << ' '; //如果不是第一个输出,则先输出一个空格
cout << i; //输出询问的编号
}
}
cout << endl;
return 0;
}