dfs判断图的连通块数量~
#include<cstdio> #include<algorithm> #include<vector> #include<cstring> using namespace std; const int maxn=1e6+14; vector<int> g[maxn]; int visit[maxn],N,M,x,y,flag; void init () { fill (visit,visit+maxn,0); for (int i=0;i<maxn;i++) g[i].clear(); } void dfs (int v) { visit[v]=true; if (g[v].size()!=2) flag=1; for (int i=0;i<g[v].size();i++) if (!visit[g[v][i]]) dfs (g[v][i]); } int dfsTrave () { int block=0; for (int i=1;i<=N;i++) if (!visit[i]) { flag=0; dfs (i); if (!flag) block++; } return block; } int main () { while (~scanf ("%d %d",&N,&M)) { init (); for (int i=0;i<M;i++) { scanf ("%d %d",&x,&y); g[x].push_back(y); g[y].push_back(x); } printf ("%d ",dfsTrave()); } return 0; }