首页 > 其他 > 详细

染色法判断二分图

时间:2021-05-11 22:18:06      阅读:22      评论:0      收藏:0      [点我收藏+]
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
struct node{
    int next,to;
}edge[maxn<<1];
int head[maxn<<1],cnt,st[maxn];
void add(int from,int to){
    edge[++cnt]={ head[from],to };
    head[from]=cnt;
}
typedef pair<int,int> PII;
bool bfs(int u){
    int hh=0,tt=0;
    PII q[maxn];
    q[0]={u,1};
    st[u]=1;
    while(hh<=tt){
        auto t=q[hh++];
        int ver=t.first,c=t.second;
        for(int i=head[ver];i;i=edge[i].next){
            int j=edge[i].to;
            if(!st[j]){
                st[j]=3-c;
                q[++tt]={j,3-c};
            }
            else if(st[j]==c)
                return false;
        }
    }
    return true;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=0,u,v;i<m;i++){
        cin>>u>>v;
        add(u,v);
        add(v,u);
    }
    bool flag=true;
    for(int i=1;i<=n;++i){
        if(!st[i]){
            if(!bfs(i)){
                flag=false;
                break;
            }
        }
    }
    puts(flag?"Yes":"No");
}

  

染色法判断二分图

原文:https://www.cnblogs.com/qq1415584788/p/14757127.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!