AcWing 860. 染色法判定二分图
原题链接
简单
作者:
东方晓
,
2021-04-02 14:01:47
,
所有人可见
,
阅读 201
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100010, M = 200010;
int e[M], ne[M], h[N], idx;
int n, m;
int color[N]; //染色数组 0,1,2
void add(int a, int b){
e[++ idx] = b, ne[idx] = h[a], h[a] = idx;
}
bool dfs(int x, int c){ //给x染色
color[x] = c;
for(int i = h[x]; i; i = ne[i]){
int y = e[i];
if(!color[y] && !dfs(y, 3 - c))
return false;
else if(color[y] == c) //奇数环
return false;
}
return true;
}
int main(){
cin >> n >> m;
while (m --){
int a, b;
scanf("%d%d", &a, &b);
add(a, b), add(b,a);
}
bool flag = true;
for (int i = 1; i <= n; i ++) //可能不连通
if(!color[i] && !dfs(i, 1)){
flag = false;
break;
}
if(flag) puts("Yes");
else puts("No");
return 0;
}