二分图的判定(模板)

采用DFS和黑白二着色的方法判定二分图

vector<int> g[maxn];//邻接表
int color[maxn];//1,2分别代表黑色和白色,0表示还没着色,调用前要把color数组初始化为0 

bool bipartite(int u) {//判断结点u所在的联通分量是否为二分图 
    for (int i = 0; i < g[u].size(); ++i) {
        int v = g[u][i];//枚举每条边(u,v) 
        if (color[v] && color[u] == color[v]) return false;//结点v已经着色,且和结点u颜色冲突 
        if (0 == color[v]) {
            color[v] = 3 - color[u];//给结点v着与结点u相反的颜色 
            if (!bipartite(v)) return false;
        }
    }
    return true;
}

改写成BFS,这样搜索不会造成栈溢出,变量的意义与之前的相同

vector<int> g[maxn];
int color[maxn];

bool bfs() {
    for (int i = 1; i <= n; ++i) {
        if (g[i].size() > 0 && 0 == color[i]) {
            queue<int> que;
            while (!que.empty()) que.pop();
            que.push(i);

            while (!que.empty()) {
                int u = que.front();
                que.pop();

                for (int i = 0; i < g[u].size(); ++i) {
                    int v = g[u][i];
                    if (color[v] && color[v] == color[u]) return false;
                    if (color[v] == 0) {
                        color[v] = 3 - color[u];
                        que.push(v);
                    }
                }
            }
        }
    }
    return true;
}

模板题 hihocoder1121
题目链接 https://vjudge.net/problem/HihoCoder-1121

#include<bits/stdc++.h>
using namespace std;

const int maxn = 10050;

int n, m;
vector<int> g[maxn];
int color[maxn];

void init() {
    memset(color, 0, sizeof(color));
    for (int i = 0; i < maxn; ++i) g[i].clear();
}

bool bfs() {
    for (int i = 1; i <= n; ++i) {
        if (g[i].size() > 0 && 0 == color[i]) {
            queue<int> que;
            while (!que.empty()) que.pop();
            que.push(i);

            while (!que.empty()) {
                int u = que.front();
                que.pop();

                for (int i = 0; i < g[u].size(); ++i) {
                    int v = g[u][i];
                    if (color[v] && color[v] == color[u]) return false;
                    if (color[v] == 0) {
                        color[v] = 3 - color[u];
                        que.push(v);
                    }
                }
            }
        }
    }
    return true;
}

int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        init();
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= m; ++i) {
            int from, to;
            scanf("%d%d", &from, &to);
            g[from].push_back(to);
            g[to].push_back(from);
        }
        bool ok = bfs();
        printf("%s\n", ok ? "Correct" : "Wrong");
    }
    return 0;
}

转载于:https://www.cnblogs.com/wafish/p/10465444.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值