AcWing 860. 染色法判定二分图
原题链接
简单
作者:
自由的犇儿哥
,
2021-03-29 20:39:04
,
所有人可见
,
阅读 276
染色法判断二分图模板
C++ 代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int n = 100100, m = 3 * n;
int h[n], ne[m], to[m],e[m],idx;
int color[n];
void addedge(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
bool dfs(int fa,int col)
{
color[fa] = col;
for (int i = h[fa]; ~i; i = ne[i])
{
int j = e[i];
if (!color[j])
{
if (!dfs(j, 3 - col))
return false;
}
else if(color[j]==col)
{
return false;
}
}
return true;
}
int N, M;
int main()
{
memset(h,-1,sizeof h);
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
int a, b;
scanf("%d%d", &a, &b);
addedge(a, b), addedge(b, a);
}
bool flag = true;
for (int i = 0; i <= n; i++)
{
if (!color[i])
{
if (dfs(i, 1) == false)
{
flag = false;
break;
}
}
}
if (flag)
puts("Yes");
else puts("No");
return 0;
}