codeforces E. Cyclic Components

题目链接如下:
http://codeforces.com/contest/977/problem/E

题目大意是说:

给你一个无向图,让你寻找该图中能够形成的环有多少个。

试着分析一下,如果要形成环,那么每一个节点的特点是什么?会发现,每一个节点的度为2,所以思路就是,建立一个图,通过搜索,保存路径,判断每一个节点的度即可。困难的地方在于:如何建立图以及如何搜索

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int Max=210000;
 4 vector<int>G[Max];
 5 vector<int>rd;
 6 int vis[Max],n,m;
 7 long long ans=0;
 8 void build()
 9 {
10     cin>>n>>m;
11     for(int i=0;i<m;i++)
12     {
13     int s,t;
14     cin>>s>>t;
15     G[s].push_back(t);
16     G[t].push_back(s);
17     }
18 }
19 void dfs(int x)
20 {
21     vis[x]=1;
22     rd.push_back(x);
23     for(int i=0;i<G[x].size();i++)
24     {
25         if(!vis[G[x][i]])
26             dfs(G[x][i]);
27     }
28 }
29 int main()
30 {
31     memset(vis,0,sizeof(vis));
32     build();
33     for(int i=1;i<=n;i++)
34     {
35         if(!vis[i])
36         {
37             bool flag=false;
38             rd.clear();
39             dfs(i);
40             for(int j=0;j<rd.size();j++)
41             {
42                 if(G[rd[j]].size()!=2)
43                 {
44                     flag=true;
45                     break;
46                 }
47             }
48             if(!flag)
49             ans++;
50 
51         }
52     }
53     printf("%lld\n",ans);
54 
55     return 0;
56 }

难点的解决方法:
通过vector建立动态数组,把每一个点与谁相邻存到数组中。通过判断有一个点与之相连,判断边的个数

通过dfs,以一个节点开始进行搜索,将路径中的所有点都找出,并且保存路径,判断即可。

猜你喜欢

转载自www.cnblogs.com/renxin123/p/9099673.html