判断给定图是否存在合法拓扑序列https://acm.sdut.edu.cn/onlinejudge3/contests/3990/problems/A本题可使用bfs来解,具体思路是:
将第一个节点入队,并标记为已访问,进行bfs,若在bfs中遇到了已访问的节点,说明该图存在环,即该图不存在合法拓扑排序。若bfs结束仍未有重复遍历的节点则该图存在合法拓扑排序。
#include<bits/stdc++.h>
using namespace std;
#define INF INT_MAX
const int N = 1e2 + 10;
#define TLE ios::sync_with_stdio(false);
int mp[N][N],vis[N];
int n, m,ans;
int a[N];
void bfs(int i)
{
int in, out;
in = out = 0;
ans = 1;
a[in++] = 1;
vis[1] = 1;
while (in > out)
{
int t = a[out++];
for (int i = 1; i <= n; i++)
{
if (mp[t][i] == 1)
{
if (vis[i] == 1)
{
ans = 0;
break;
}
else
{
vis[i] = 1;
a[in++] = i;
}
}
}
}
if (ans == 1)cout << "YES" << endl;
else cout << "NO" << endl;
}
int main()
{
int x, y;
while (cin >> n >> m)
{
memset(vis, -1, sizeof(vis));
memset(mp, 0, sizeof(mp));
ans = 1;
while (m--)
{
cin >> x >> y;
mp[x][y] = 1;
}
bfs(1);
}
return 0;
}