【算法3.11】二分图 - 染色法(完结)

目录

一、二分图概念

二、860. 染色法判定二分图 

1、dfs

2、bfs


一、二分图概念

 

二、860. 染色法判定二分图 

活动 - AcWing

1、dfs

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

const int N=1e5+10,M=2e5+10;
int h[N],e[M],ne[M],idx;
int color[N];//保存各个点的颜色0未染色 1是红 2是黑
int n,m;

void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

bool 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)) return false;//实现1和2颜色的转化
        }
        else if(color[j]==c) return false; //如果跟该点相邻的点颜色也相同 则不是二分图
    }
    return true;
}

int main()
{
    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);
    }
    
    for(int i=1;i<=n;i++)
        if(!color[i])
            if(!dfs(i,1)) 
            {
                puts("No");
                return 0;
            }
    puts("Yes");
    return 0;
}

2、bfs

 

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

typedef pair<int,int> PII;
const int N=1e5+10,M=2e5+10;
int h[N],e[M],ne[M],idx;
int color[N];//保存各个点的颜色0未染色 1是红 2是黑
int n,m;

void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

bool bfs(int u)
{
    int hh=0,tt=0;
    PII q[N];
    q[0]={u,1};
    color[u]=1;
    
    while(hh<=tt)
    {
        auto t=q[hh++];
        int v=t.first,c=t.second;
        for(int i=h[v];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(!color[j])
            {
                color[j]=3-c;
                q[++tt]={j,3-c};
            }
            else if(color[j]==c) return false;
        }
    }
    return true;
}

int main()
{
    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);
    }
    
    for(int i=1;i<=n;i++)
        if(!color[i])
            if(!bfs(i)) 
            {
                puts("No");
                return 0;
            }
    puts("Yes");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值