染色法判断二分图 - BFS 实现
作者:
lazy_go
,
2022-04-13 16:28:20
,
所有人可见
,
阅读 214
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1e5 + 10, M = 2e5 + 10;
int e[M], ne[M], h[N], idx;
enum Status {
WHITE, GRAY, BLACK
};
enum Color {
RED, BLUE
};
Status status[N];
Color color[N];
void addArc(int x, int y){
e[idx] = y;
ne[idx] = h[x];
h[x] = idx ++;
}
bool bfs(int u){
queue<int> q;
q.push(u);
color[u] = RED;
status[u] = GRAY;
while(!q.empty()){
int v = q.front();
q.pop();
Color cur = color[v] == RED ? BLUE : RED;
for(int i = h[v]; i != -1; i = ne[i]){
int j = e[i];
if(status[j] == WHITE){
status[j] = GRAY;
q.push(j);
color[j] = cur;
}else {
if(color[j] != cur)return false;
}
}
status[v] = BLACK;
}
return true;
}
int main(){
int n,m,x, y;
cin >> n >> m;
memset(h, -1,sizeof h);
for(int i = 0; i < m; i ++){
cin >> x >> y;
addArc(x, y);
addArc(y, x);
}
bool res = true;
for(int i = 1; i <= n; i ++){
if(status[i] == WHITE){
res = res && bfs(i);
if(!res)break;
}
}
if(res)puts("Yes");
else puts("No");
return 0;
}