二分图中不存在奇数环。
环中的点的数量一定要是1号颜色和2号颜色点的数量一致,否则矛盾
DFS
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 2e5 + 10;
int h[N], e[N],ne[N],idx;
int n,m;
int dis[N];
// int g[N]
int color[N];
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int dfs(int u, int c){
color[u] = c;
for(int i = h[u]; i!=-1; i = ne[i]){
int j =e[i];
if(!color[j]){
if(!dfs(j,3-c)){//通过3-c,来实现染1号色,和染2号色
return false;
}
}
else if(color[j] == c){//如果一条边上的两个点颜色相同,则矛盾
return false;
}
}
return true;
}
int main(){
scanf("%d%d",&n,&m);
memset(h,-1,sizeof(h));
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]){
if(!dfs(i,1)){
flag = false;
break;
}
}
}
if(flag) puts("Yes");
else puts("No");
return 0;
}
BFS
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int,int> pii;
const int N = 2e5 + 10;
int h[N], e[N],ne[N],idx;
int n,m;
int dis[N];
pii q[N];
int color[N];
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
// int dfs(int u, int c){
// color[u] = c;
// for(int i = h[u]; i!=-1; i = ne[i]){
// int j =e[i];
// if(!color[j]){
// if(!dfs(j,3-c)){//通过3-c,来实现染1号色,和染2号色
// return false;
// }
// }
// else if(color[j] == c){//如果一条边上的两个点颜色相同,则矛盾
// return false;
// }
// }
// return true;
// }
int bfs(int u){
int hh = 0, tt = 0;
q[0] = {u,1};
color[u] = 1;
while(hh <= tt){
pii t = q[hh++];
int ver = t.x, ys = t.y;
for(int i = h[ver]; i != -1; i = ne[i]){
int j = e[i];
if(!color[j]){
color[j] = 3-ys;
q[++tt] = {j,color[j]};
// q.push({j,color[j]});
}
else if(color[j] == ys){
return false;
}
}
}
return true;
}
int main(){
scanf("%d%d",&n,&m);
memset(h,-1,sizeof(h));
while(m--){
int a,b;
scanf("%d%d",&a,&b);
add(a,b),add(b,a);
}
bool flag = true;
queue<int> q;
int c = 1;
for(int i = 1; i <= n; i++){
if(!color[i]){
if(!bfs(i)){
flag = false;
break;
}
}
}
if(flag) puts("Yes");
else puts("No");
return 0;
}