染色法判定二分图(bfs)
作者:
amagi
,
2023-10-06 17:14:01
,
所有人可见
,
阅读 93
#include <iostream>
#include <queue>
#include <cstring>
#define PII pair<int,int>
using namespace std;
const int N = 2e5 + 10;
int ne[N],e[N],h[N],idx;
int dx[N];
int n,m;
void add(int a,int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
bool bfs(int a,int b){
queue<PII> op;
op.push(make_pair(a,b));
dx[a] = b;
while(op.size()){
auto pp = op.front();
op.pop();
int aa = pp.first;
int bb = pp.second;
for(int i = h[aa]; i != -1; i = ne[i]){
int uu = e[i];
if(dx[uu] == 0){
op.push(make_pair(uu,3 - bb));
dx[uu] = 3 - bb;
}
else{
if(dx[uu] == bb) return 1;
}
}
}
return 0;
}
void solve(){
memset(h,-1,sizeof h);
cin >> n >> m;
for(int i = 1; i <= m; i ++){
int a,b;
cin >> a >> b;
add(a,b);
add(b,a);
}
bool kk =true;
for(int i = 1; i <= n; i ++){
if(dx[i] == 0){
if(bfs(i,1)) kk = false;
if(kk == false) break;
}
}
if(kk) cout << "Yes\n";
else cout << "No\n";
return;
}
int main(){
solve();
return 0;
}