Jiudu question 1448: Legal or Not, 1448 legal
This article uses topological sorting to determine whether a ring exists. If the number of output nodes is less than N, a ring is formed, which is almost the same as the previous Code 1449.
Question link http://ac.jobdu.com/problem.php? Pid = 1, 1448
Reprinted please indicate this article address http://blog.csdn.net/yangnanhai93/article/details/41226369
#include <iostream>#include <memory.h>#include <queue>using namespace std;int A[100],MapCount[100][100];bool TopoSort(int n){ queue<int> qu; for(int i=0;i<n;i++) if(A[i]==0) qu.push(i); int count=0; while(!qu.empty()) { int front=qu.front(); qu.pop(); count++; for (int i=0;i<n;i++) { if(MapCount[front][i]) { A[i]--; if(A[i]==0) qu.push(i); } } } if(count==n) return true; else return false;}int main(){ //freopen("data.in","r",stdin); int m,n,x,y; while(cin>>m>>n&&m) { memset(A,0,sizeof(A)); memset(MapCount,0,sizeof(MapCount)); for(int i=0;i<n;i++) { cin>>x>>y; MapCount[x][y]=1; } for(int i=0;i<m;i++) for(int j=0;j<m;j++) if(MapCount[i][j]!=0) A[j]++; if(TopoSort(m)) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0;}/************************************************************** Problem: 1448 User: vincent_ynh Language: C++ Result: Accepted Time:10 ms Memory:1560 kb****************************************************************/