Legal or Not 拓扑加邻接表 hdu
#include <stdio.h>#include <cstring>#include <queue>#include <iostream>using namespace std;const int maxn=101;struct edge{ int from,to,next;} e[maxn<<1];int head[maxn];int in[maxn];int n,t,m;bool topsort(){ queue <int> q; for(int i=0; i<n; i++) if(in[i]==0) q.push(i); int nodenum=0; while(!q.empty()) { int v=q.front(); q.pop(); nodenum++; for(int i=head[v]; i!=-1; i=e[i].next) { int u=e[i].to; in[u]--; if(in[u]==0) q.push(u); } } if(nodenum<n) return false; return true;}void add(int i,int j){ e[t].from=i; e[t].to=j; e[t].next=head[i]; head[i]=t++;}int main(){ int a,b; while(scanf("%d%d",&n,&m)==2) { if(n==0&&m==0) break; t=0; memset(in,0,sizeof(in)); memset(head,-1,sizeof(head)); for(int i=1; i<=m; i++) { scanf("%d%d",&a,&b); add(a,b); in[b]++; } if(topsort()) printf("YES\n"); else printf("NO\n"); } return 0;}