Bipartite graph learning - basic dfs to judge bipartite graph

#include <iostream>
#include <cstdio>
#include <string.h>
#include <vector>
#define inf 0xfffffff

using namespace std;
const int maxn = 1e5 + 1e2;
const int maxp = 1e3 + 1e2;
//Adjacency list vector implementation
vector<int> G[maxp];
int color[maxp];
int n,m;

void init()
{
    memset(color,0,sizeof(color));
    for(int i = 0;i <= n;i++)
    {
        G[i].clear();
    }
}

bool dfs(int s,int clr)
{
    color[s] = clr;

    for(int i  = 0;i < G[s].size();i++)
    {
        int to = G[s][i];

        if(color[to] == clr)return false;

        if(color[to] == 0 && !(dfs(to,-clr)))return false;

    }
    return true;
}
void solve()
{
    for(int i = 0;i < n;i++)
    {
        if(color[i] == 0)
        {
            if(!dfs(i,1))
            {
                printf("No\n");
                return;
            }
        }
    }
    printf("Yes\n");
    return;
}
intmain()
{
    while(cin >> n >> m)
    {
        init();
        for(int i = 0;i < m;i++)
        {
            int a,b;
            cin>>a>>b;
            G[a].push_back(b);
            G[b].push_back(a);
        }
        solve();
    }

    return 0;
}


The general idea of ​​the algorithm is that there are only two colors 1-1 for dichromatic coloring of the current image. Starting from an uncolored point, dfs will colorize the current point first, and then make the following judgments for all subsequent points. A point has been dyed and has the same color as the current one - "not a bipartite, not the same -" ignore it and ignore it

If the next point is not dyed, try to dye it. If the dyeing fails, it will still fail after going back.

The dyeing is successful, regardless of him, continue to dye

The above is a loop until the solve function can't find a point that can be dyed

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324673953&siteId=291194637