E. Cyclic Components (DFS)(Codeforces Round #479 (Div. 3))

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn = 2*1e5+5;
 5 vector<int>p[maxn];
 6 vector<int>c;
 7 bool check[maxn];
 8 
 9 
10 void dfs(int x) {
11     check[x] = true;
12     c.push_back(x);
13     for (int i = 0; i < p[x].size(); i++) {
14         int y = p[x][i];
15         if (!check[y]) {
16             dfs(y);
17         }
18     }
19 }
20 
21 int main() {
22     ios_base::sync_with_stdio(false);
23     cin.tie(0);
24 
25     int n, m;
26     cin >> n >> m;
27     for (int i = 0; i < m; i++) {
28         int u, v;
29         cin >> u >> v;
30         p[u].push_back(v);
31         p[v].push_back(u);
32     }
33     int ans = 0;
34     for (int i = 1; i <= n; i++) {
35         if (!check[i]) {
36             c.clear();
37             dfs(i);
38             bool flag = true;
39             for (int k = 0; k < c.size(); k++) {
40                 if (p[c[k]].size() != 2) {
41                     flag = false;
42                     break;
43                 }
44             }
45             if(flag)
46                 ans++;
47         }
48     }
49     cout << ans << endl;
50     return 0;
51 }
原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/9004746.html