染色法判定二分图 -2025/11/12
染色法判定二分图
#include<bits/stdc++.h>
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 dfs(int u, int x){
color[u] = x;
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(!color[j]){
if(!dfs(j, 3 - x)) return false;
}
else if(color[j] == x) return false;
}
return true;
}
int main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
memset(h , -1 , sizeof h);
cin >> n >> m;
while(m --){
int a, b;
cin >> a >> b;
add(a,b), add(b ,a);
}
int res = 0;
int flag = 0;
for(int i = 1; i <= n; i++){
if(!color[i]){
if(!dfs(i , 1)) {
flag = 1;
break;
}
}
}
if(flag) puts("No");
else puts("Yes");
return 0;
}

浙公网安备 33010602011771号