跳到正文

算法·理论

二分图学习笔记 Step1——判定

Stars_visitor_tyw约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年12月1日
收录
2026年5月25日
更新
2026年11月9日
篇幅
约 2 分钟

版本

  1. v1当前

二分图

定义

对于一张无向图 GG,若所有点可以分为两个点集 AA 和 BB,且点集内的点没有连边,那么我们称 GG 可以划分为一张二分图。

注意:二分图的划分不一定唯一,二分图不一定连通。

二分图存在的充分必要条件

若无向图 GG 是二分图,那么 GG 没有奇环。

若无向图 GG 没有奇环,那么 GG 是二分图。

二分图的判定

染色法:枚举没有访问的点开始 dfs。dfs 遍历点时,用 11 和 22 两种颜色交替给结点染色。若出现一个点 xx 的邻接点 yy 访问过,且 colorx=colorycolor_x = color_y,则出现奇环,不是二分图。所有点染色后,若都没有出现奇环,则是二分图。

模板题——UVA10004

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
#define N 10005
vector<int> nbr[N];
int n, m, color[N];
bool dfs(int cur, int color_cur)
{
	color[cur]=color_cur;
	for(int nxt:nbr[cur])
	{
		if(color[nxt]==color_cur)
		{
			return 0;
		}
		if(color[nxt]==0)
		{
			if(!dfs(nxt,3-color_cur))return 0;
		}
	}
	return 1;
}
signed main()
{
	while(cin>>n)
	{
		if(!n)break;
		cin>>m;
		for(int i=1;i<=n;i++)color[i]=0,nbr[i].clear();
		for(int i=1;i<=m;i++)
		{
			int x, y;
			cin>>x>>y;
			x++,y++;
			nbr[x].push_back(y);
			nbr[y].push_back(x);
		}
		bool f=1;
		for(int i=1;i<=n;i++)
		{
			if(color[i])continue;
			if(!dfs(i,1))
			{
				cout<<"NOT BICOLORABLE.\n";
				f=0;
				break;
			}
		}
		if(f)cout<<"BICOLORABLE.\n";
	}
}
原文