acwing 860 染色法判定二分图

题面

在这里插入图片描述

题解

  1. 二分图定义:图中点可分为两个集合,每个集合中的点互不相邻
    二分图性质:当且仅当图中不含奇数环(充要条件)

在这里插入图片描述
2. 对于染色过程,我们用树/图的深度遍历,如果当前节点没有染色,就将其染成1,然后与它相邻的节点染成2,这样就不会发生冲突;如果在染色的过程中发生冲突,它的相邻节点已经染色并且颜色相同,说明染色失败。

3.如图,对于图中存在奇数环的图,一定会发生染色冲突,不存在奇数环的图,一定不会发生染色冲突

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;

int n, m;
int h[N], e[2 * N], ne[2 * N], idx;
int color[N];   //表示每个点的颜色(0表示未染色,1,2表示两种不同的颜色)

void add(int a, int b) {
    
    
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx++;
}

//u表示当前节点,c表示当前点的颜色
bool dfs(int u, int c) {
    
    
    color[u] = c;  //染色
    //给所有连通块都染色(树的深度遍历)
    for (int i = h[u]; i != -1; i = ne[i]) {
    
    
        int j = e[i];
        if (!color[j]) {
    
      //未染色
            if (!dfs(j, 3 - c)) {
    
      //染色冲突
                return false;
            }
        } else if (color[j] == c) {
    
      //染色相同
            return false;
        }
    }
    return true;
}

bool check() {
    
    
    bool flag = true;
    for (int i = 1; i <= n; i++) {
    
    
        if (!color[i]) {
    
       //未染色
            if (!dfs(i, 1)) {
    
      //染色发生冲突
                flag = false;
                break;
            }
        }
    }
    return flag;
}


int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    memset(h, -1, sizeof h);

    cin >> n >> m;

    while (m--) {
    
    
        int a, b;
        cin >> a >> b;
        add(a, b), add(b, a);
    }

    if (check()) cout << "Yes" << endl;
    else cout << "No" << endl;


    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114558381