Test instructions: To judge whether there is no loop;
Idea: topological sequencing;
Two types of notation:
struct + pointer:
#include <stdio.h> #include <string.h> #include <algorithm>using namespace Std;int n,m;struct node{ int du; Node *next;} Q[50010];int topo () {node *p; int *shu=new int[50010]; int i,j,k=0,num; while (1) {num=0; memset (Shu,0,sizeof (SHU)); for (i=0;i<n;i++) {if (q[i].du==-1) continue; if (q[i].du==0) {shu[num++]=i; Q[i].du=-1; k++; }} if (Num==0&&k<=n) return 0; if (k==n) return 1; for (i=0;i<num;i++) {p=q[shu[i]].next; while (p) {q[p->du].du--; p=p->next; }}}}int Main () {int a,b,i,k,j; while (scanf ("%d%d", &n,&m)!=eof) {if (n==0&&m==0) break; for (i=0;i<n;i++) {q[i].du=0; Q[i].next=null; } for (i=0;i<m;i++) { scanf ("%d%d", &a,&b); q[a].du++; Node *t=new node; t->du=a; t->next=q[b].next; q[b].next=t; } if (topo ()) printf ("yes\n"); else printf ("no\n"); } return 0;}STL, queue:
#include <stdio.h> #include <string.h> #include <queue> #include <algorithm>using namespace std ; int con[500010],n,m;vector<int> G[500010];int topo () { int sum=n; queue<int> Q; int flag=0; for (int i=0;i<n;i++) if (con[i]==0) Q.push (i); while (!q.empty ()) { sum--; int J=q.front (); Q.pop (); for (int k=0;k<g[j].size (); k++) { if (--con[g[j][k]]==0) Q.push (G[j][k]); } } if (sum>0) return 0; else return 1;} int main () { int i,j,k,a,b; while (scanf ("%d%d", &n,&m)!=eof) { if (n==0&&m==0) break; for (i=0;i<=n;i++) { con[i]=0; G[i].clear (); } for (i=0;i<m;i++) { scanf ("%d%d", &a,&b); G[a].push_back (b); con[b]++; } if (topo ()) printf ("yes\n"); else printf ("no\n"); } return 0;}
HDU 3342 Legal or not