目录
一、二分图概念
二、860. 染色法判定二分图
1、dfs
#include <cstring>
#include <iostream>
using namespace std;
const int N=1e5+10,M=2e5+10;
int h[N],e[M],ne[M],idx;
int color[N];//保存各个点的颜色0未染色 1是红 2是黑
int n,m;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
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;//实现1和2颜色的转化
}
else if(color[j]==c) return false; //如果跟该点相邻的点颜色也相同 则不是二分图
}
return true;
}
int main()
{
memset(h,-1,sizeof h);
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
}
for(int i=1;i<=n;i++)
if(!color[i])
if(!dfs(i,1))
{
puts("No");
return 0;
}
puts("Yes");
return 0;
}
2、bfs
#include <cstring>
#include <iostream>
using namespace std;
typedef pair<int,int> PII;
const int N=1e5+10,M=2e5+10;
int h[N],e[M],ne[M],idx;
int color[N];//保存各个点的颜色0未染色 1是红 2是黑
int n,m;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
bool bfs(int u)
{
int hh=0,tt=0;
PII q[N];
q[0]={u,1};
color[u]=1;
while(hh<=tt)
{
auto t=q[hh++];
int v=t.first,c=t.second;
for(int i=h[v];i!=-1;i=ne[i])
{
int j=e[i];
if(!color[j])
{
color[j]=3-c;
q[++tt]={j,3-c};
}
else if(color[j]==c) return false;
}
}
return true;
}
int main()
{
memset(h,-1,sizeof h);
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
}
for(int i=1;i<=n;i++)
if(!color[i])
if(!bfs(i))
{
puts("No");
return 0;
}
puts("Yes");
return 0;
}