图中找环

 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 }

 

posted @ 2018-08-13 18:41  LeeSongt  阅读(741)  评论(0编辑  收藏  举报