D24 二分图判定 染色法

视频链接:https://www.bilibili.com/video/BV1sZ4y1i7NZ

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=100010,M=2*N;
int n,m;
struct edge{int v,ne;}e[M];
int h[N],idx;
int color[N];

void add(int a,int b){
  e[++idx]={b,h[a]};
  h[a]=idx;
}
bool dfs(int u,int c){
  color[u]=c;
  for(int i=h[u];i;i=e[i].ne){
    int v=e[i].v;
    if(!color[v]){
      if(dfs(v,3-c))return 1;
    }
    else if(color[v]==c)return 1;//有奇环
  }
  return 0;
}
int main(){
  cin>>n>>m;
  for(int i=0;i<m;i++){
    int a,b;
    cin>>a>>b;
    add(a,b); 
    add(b,a);
  }
  bool 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;
}

 

posted @ 2022-06-28 08:04  董晓  阅读(451)  评论(0编辑  收藏  举报