Codeforce 977E Cyclic Components

dfs判断图的连通块数量~

#include
#include
#include
#include
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) g[i].clear();
}
void dfs (int v) {
    visit[v]=true;
    if (g[v].size()!=2) flag=1;
    for (int i=0;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) {
            scanf ("%d %d",&x,&y);
            g[x].push_back(y);
            g[y].push_back(x);
        }
        printf ("%d\n",dfsTrave());
    }
    return 0;
}

 

你可能感兴趣的:(Codeforce 977E Cyclic Components)