无向图 找连通分量是圈的分量个数

#include 

#define INF 0x3f3f3f3f
#define eps 1e-5

typedef long long LL;
const double pi = acos(-1.0);
const long long mod = 25 * 1E8;
using namespace std;

const int N = 200 * 1000 + 5;

int deg[N];
bool used[N];
vector <int> g[N];
vector <int> comp;

void dfs(int v)
{
    used[v] = true;
    comp.push_back(v);
    for(int i = 0;i < g[v].size();i++)
        if(!used[g[v][i]])
            dfs(g[v][i]);
}


int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    ios_base::sync_with_stdio(0);cin.tie(0);
    int N,M;
    cin >> N >> M;
    int a,b;
    //memset(deg,0,sizeof(deg));
    //memset(g,0,sizeof(g));
    //memset(used,0,sizeof(used));
    //comp.clear();
    for(int i = 0;i < M;i++)
    {
        cin >> a >> b;
        --a;
        --b;
        g[a].push_back(b);
        g[b].push_back(a);
        deg[a]++;
        deg[b]++;
    }

    int ans = 0;
    for(int i = 0;i < N;i++)
    {
        if(!used[i])
        {
            comp.clear();
            dfs(i);
            bool ok = true;
            for(int j = 0;j < comp.size();j++)
                ok &= (deg[comp[j]] == 2);
            if(ok)
                ans++;
        }
    }
    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(简单图论)