#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 110;
const int maxm = 110*110;
struct Edge
{
int v;
int next;
}edge[maxm];
int cnt;
int tot;
int n, m;
int first[maxn];
int ind[maxn];
int topo[maxn];
void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u], first[u] = cnt++;
}
void init()
{
cnt = 0;
tot = 0;
memset(first, -1, sizeof(first));
memset(ind, 0, sizeof(ind));
}
int read_case()
{
init();
scanf("%d%d", &n, &m);
if(!n) return 0;
return 1;
}
int toposort()
{
for(int i = 0; i < n; i++)
{
int c = 0, u;
for(int j = 0; j < n; j++)
{
if(!ind[j]) { u = j; c++;}
}
if(c == 0) return -1;
ind[u] = -1;
topo[u] = u;
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
ind[v]--;
}
}
return 1;
}
void solve()
{
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
ind[v]++;
}
int ans = toposort();
if(ans == -1) printf("NO\n");
else printf("YES\n");
}
int main()
{
while(read_case())
{
solve();
}
return 0;
}
拓扑排序模板
最新推荐文章于 2024-08-08 10:23:22 发布