传送门:Legal or Not
拓扑排序判环。
#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e2+2;
int n, m;
vector<int> g[maxn];
int indeg[maxn];
void init()
{
for(int i = 0; i < maxn; ++i)
g[i].clear(), indeg[i] = 0;
}
void read()
{
int u, v;
for(int i = 0; i < m; ++i)
{
cin >> u >> v;
g[u].push_back(v);
++indeg[v];
}
}
bool topoSort()
{
queue<int> q;
for(int i = 0; i < n; ++i)
if(!indeg[i])
q.push(i);
int cnt = 0;
while(!q.empty())
{
int u = q.front();
q.pop();
++cnt;
for(int i = 0; i < g[u].size(); ++i)
if(!(--indeg[g[u][i]]))
q.push(g[u][i]);
}
if(cnt < n)
return 0;
return 1;
}
void solve()
{
if(topoSort())
cout << "YES\n";
else
cout << "NO\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
while(cin >> n >> m && n)
{
init();
read();
solve();
}
return 0;
}