AcWing 860. 染色法判定二分图
原题链接
简单
作者:
Asiim0v
,
2021-05-14 19:48:14
,
所有人可见
,
阅读 336
C++ BFS解法
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10, M = 2 * N;
int h[N], e[M], ne[M], idx;
int n, m;
int color[N];
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool bfs(){
queue<int> q;
// 保证每个点都被染色
for(int i = 1; i <= n; ++i){
// 只要遇到没染色的点就直接染成0, 因为这一定是一个新的连通块
if(color[i] == -1){
color[i] = 0;
q.push(i);
while(!q.empty()){
auto t = q.front(); q.pop();
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(color[j] == -1){
color[j] = !color[t];
q.push(j);
}
else if(color[j] == color[t]) return false;
}
}
}
}
return true;
}
int main()
{
cin >> n >> m;
memset(color, -1, sizeof(color));
memset(h, -1, sizeof(h));
while(m--){
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
bool flag = bfs();
if(flag) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}