染色判断二分图

rt

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

vector<vector<int>>ev;
vector<int>color;
vector<bool>visited;


bool checkB(int start){
    queue<int> Q;
    Q.push(start);
    color[start] = 1;
    visited[start] = true;//开始弄成1
    while(!Q.empty()){
        int now = Q.front();//从队列取出
        Q.pop();
        for(int x:ev[now]){
            if(!visited[x]){//如果没有访问过,把他染色成对立颜色
                color[x] = -color[now];
                visited[x] = true;
                Q.push(x);
            }
            else if(color[x] == color[now]){//访问过如果同颜色说明不是二分图
                return false;
            }
        }
    }
    return true;//别忘了
}

int main()
{
    int n,m,a,b;
    cin >> n >> m;
    ev.resize(n+1);
    while (m -- ){
        cin >> a >> b;
        ev[a].push_back(b);
        ev[b].push_back(a);
        if(a==b){//自环直接就不是二分图
            cout << "No";
            return 0;
        }
    }
    color.resize(n+1);
    visited.resize(n+1);
    for (int i = 0; i <= n; i ++ ){
        color[i] = 0;
        visited[i] = false;
    }
    int real = 1;
    for (int i = 1; i <= n; i ++ ){
        if(!visited[i]){
            if(!checkB(i)){
                real = 0;
                break;
            }
        }
    }
    if(real)cout<<"Yes";
    else cout << "No";
    return 0;
}
posted @ 2025-08-22 17:57  .N1nEmAn  阅读(13)  评论(0)    收藏  举报