染色法判二分图(BFS/DFS c++解)

题目传送门: https://www.acwing.com/problem/content/862/

思路:

1. 对任意一未染色的顶点染色,用color数组存储颜色(color[i] = 1/2)。

2. 判断该点相邻的顶点中,是否存在未染色的点,如果还没有染色就将其染上与当前点不同的颜色;

3. 如果已经染色且颜色和相邻顶点的颜色相同则说明出现冲突,显然不是二分图;

以下分别为BFS和DFS解法:

BFS:

//Author 荣荣
//Time 2023.10.31 11:04
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010 * 2;
int n,m,ind,h[N],e[N],nex[N],color[N];

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

bool bfs(int u,int c){
    queue<int> q;
    color[u] = c;
    q.push(u);
    while (!q.empty()){
        int top = q.front(); q.pop();
        for (int i = h[top]; ~i; i = nex[i]){
            int j = e[i];
            if (color[j] != 0 && color[j] == color[top]) return false;
            if (color[j] == 0){
                color[j] = 3 - color[top];
                q.push(j);
            }
        }
    }
    return true;
}

int main()
{
	ios::sync_with_stdio(false);
    memset(h, -1, sizeof h);
	cin >> n >> m;
    for (int i = 0; i < m; i ++){
    	int u,v; cin >> u >> v; 
    	add(u,v); add(v,u);
	}

	for (int i = 1; i <= n; i ++){
	    if (color[i]) continue;
		if (!bfs(i, 1)){
			cout << "No" << endl;
			return 0;
		}
	}
	cout << "Yes" << endl;
 	return 0;
	
}

DFS:

//Author 荣荣
//Time 2023.10.31 11:05
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010 * 2;
int n,m,ind,h[N],e[N],nex[N],color[N];

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

bool dfs(int u, int c){
    color[u] = c;
    for (int i = h[u]; ~i; i = nex[i]){
        int j = e[i];
        if (color[j] && color[j] != 3 - c) return false;
        if (!color[j] && !dfs(j, 3 - c))   return false;
    }
    return true;
}

int main()
{
	ios::sync_with_stdio(false);
    memset(h, -1, sizeof h);
	cin >> n >> m;
    for (int i = 0; i < m; i ++){
    	int u,v; cin >> u >> v; 
    	add(u,v); add(v,u);
	}

	for (int i = 1; i <= n; i ++){
	    if (color[i]) continue;
		if (!dfs(i, 1)){
			cout << "No" << endl;
			return 0;
		}
	}
	cout << "Yes" << endl;
 	return 0;
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值