1. 程式人生 > >圖中找環

圖中找環

lin tdi con span freopen 判斷 eof print ==

 1 /*
 2   Source   :hihocoder 215周
 3   Problem  :有向圖判斷是否存在環
 4   Solution : 方法1. 可以使用拓撲排序來做
 5              方法2. 對於無向圖可以用並查集做
 6              方法3. 利用dfs遍歷,第一次遍歷到節點是著灰色,離開節點時著黑色,如果遍歷的過程中訪問到灰色的節點則存在環。
 7   Date     :2018-08-13-18.27
 8 */
 9 
10 #include <bits/stdc++.h>
11 using namespace std;
12 
13
typedef long long LL; 14 const int MAXN = 100005; 15 const LL MOD7 = 1e9+7; 16 17 vector<int> g[MAXN]; 18 int vis[MAXN]; 19 int n,m; 20 21 bool dfs(int u) 22 { 23 vis[u]=1; 24 for (int v:g[u]) 25 { 26 if (vis[v]==1) return true; 27 if (!vis[v] && dfs(v)) return
true; 28 } 29 vis[u]=2; 30 return false; 31 } 32 33 bool hasCircle() 34 { 35 for (int i=1;i<=n;++i) 36 { 37 if (!vis[i] && dfs(i)) return true; 38 } 39 return false; 40 } 41 42 43 int main() 44 { 45 #ifndef ONLINE_JUDGE 46 freopen("test.txt","r",stdin);
47 #endif // ONLINE_JUDGE 48 int Case; 49 scanf("%d",&Case); 50 while (Case--) 51 { 52 scanf("%d%d",&n,&m); 53 for (int i=1;i<=n;++i) g[i].clear(); 54 int u,v; 55 for (int i=1;i<=m;++i) 56 { 57 scanf("%d%d",&u,&v); 58 g[u].push_back(v); 59 } 60 memset(vis,0,sizeof(vis)); 61 if (hasCircle()) printf("YES\n"); 62 else printf("NO\n"); 63 } 64 return 0; 65 }

圖中找環