Cyclic Components CodeForces - 977E
分析:DFS 如果其中一个连通图的所有点的度数都为2就符合题意(搜索完某一连通图就把该连通图的所有点做标记,不再访问)
代码:
#include<bits/stdc++.h> using namespace std; const int N = 200000 + 5; vector<int> a[N]; int vis[N]; int flag = 1; void dfs(int cur) { vis[cur] = 1; if(a[cur].size() != 2) flag = 0; for(int i : a[cur]) { if(!vis[i]) dfs(i); } } int main() { int n, m; scanf("%d%d", &n, &m); int x, y; for(int i = 0; i < m; i++) { scanf("%d%d", &x, &y); a[x].push_back(y); a[y].push_back(x); } memset(vis, 0, sizeof(vis)); int ans = 0; for(int i = 1; i <= n; i++) { flag = 1; if(!vis[i]) { dfs(i); if(flag) ans++; } } printf("%d ", ans); return 0; }