Codeforce 977E Cyclic Components

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\n",dfsTrave());
    }
    return 0;
}

 

posted @ 2020-02-13 22:11  zlc0405  阅读(100)  评论(0编辑  收藏  举报