by   GeneralLiu  

 

染色法

 

非常容易写

 

先记录边

遍历节点

如果没有深搜过

那深搜它就是了

并染色

染为 1 和 -1 

如果染色冲突 则 return false

最后 return true

 

代码

 

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
#define N 1000
#define M 2000
int col[N],cnt,n,m,head[N],to[M],next[M];
void add(int x,int y){
    next[++cnt]=head[x];
    to[cnt]=y;
    head[x]=cnt;
}
void dfs(int u,int c){
    col[u]=c;
    for(int v,i=head[u];i;i=next[i]){
        v=to[i];
        if(!col[v])
          dfs(v,-c); // 染 -c 
        if(col[v]==col[u]){ // 有冲突 
            printf("NO");
            exit(0);
        }
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(int x,y,i=1;i<=m;i++){
        scanf("%d%d",&x,&y);
        add(x,y);
        add(y,x);
    }
    for(int i=1;i<=n;i++)
        if(!col[i])
            dfs(i,1); // 默认 染色 1 
    printf("YES");
    return 0;
}
View Code

相关文章:

  • 2022-01-09
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2021-09-27
  • 2021-09-27
  • 2021-09-27
猜你喜欢
  • 2021-06-09
  • 2022-12-23
  • 2022-03-01
  • 2021-09-29
  • 2021-12-02
  • 2022-02-02
  • 2021-09-27
相关资源
相似解决方案