hdoj-3342-Legal or Not(拓扑排序)
1 /* 2 Name:hdoj-3342-Legal or Not 3 Copyright: 4 Author: 5 Date: 2018/4/11 15:59:18 6 Description: 7 判断是否存在环 8 */ 9 #include <iostream> 10 #include <queue> 11 #include <vector> 12 #include <cstring> 13 #include <algorithm> 14 using namespace std; 15 const int MAXN = 1e+5; 16 int du[MAXN], n , m, L[MAXN]; 17 vector<int> g[MAXN]; 18 bool topsort() { 19 memset(du, 0, sizeof(du)); 20 for (int i=0; i<n; i++) { 21 for (int j=0; j<g[i].size(); j++) { 22 du[g[i][j]]++; 23 } 24 } 25 int tot = 0; 26 queue<int> Q; 27 for (int i=0; i<n; i++) { 28 if (!du[i]) { 29 Q.push(i); 30 } 31 } 32 while (!Q.empty()) { 33 int x = Q.front(); 34 Q.pop(); 35 L[tot++] = x; 36 for (int j=0; j<g[x].size(); j++) { 37 int t = g[x][j]; 38 du[t]--; 39 if (!du[t]) { 40 Q.push(t); 41 } 42 } 43 } 44 if (tot == n) return 1; 45 return 0; 46 } 47 int main() 48 { 49 while (cin>>n>>m && (m || n)) { 50 memset(L, 0, sizeof(L)); 51 memset(g, 0, sizeof(g)); 52 for (int i=0; i<m; i++) { 53 int a, b; 54 cin>>a>>b; 55 g[a].push_back(b); 56 } 57 if (topsort() == 1) cout<<"YES"<<endl; 58 else cout<<"NO"<<endl; 59 } 60 return 0; 61 }