题目点我
给出一个图,判断他是不是二分图。即能否将图的所有顶点分为两个集合,使得每条边的两个端点都属于不同集合。
做法是用广度优先搜索(BFS)。下面约定每个顶点的三个状态:白色为没有考虑过的顶点,灰色为等待处理(队列中)的顶点,黑色为已经处理过(已经弹出队列)的顶点。
每次拓展队列顶端的顶点
v
,对于
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#include <stack>
#include <vector>
#include <utility>
#include <cmath>
using namespace std;
#define N 205
vector<int> V[N];
char color[N];
int set[N];
bool bfs(){
memset(color, 'w', sizeof(color));
memset(set, 0, sizeof(set));
queue<int> Q;
int now = 0;
Q.push(now);
color[now] = 'g';
while(!Q.empty()){
now = Q.front();
Q.pop();
color[now] = 'b';
for(int i = 0; i < V[now].size(); i++){
int adj = V[now][i];
if(color[adj] == 'w'){
color[adj] = 'g';
set[adj] = set[now] ^ 1;
Q.push(adj);
}
else{
if(set[adj] == set[now])
return false;
}
}
}
return true;
}
int main(){
int n, m;
while(scanf("%d%d", &n, &m) != EOF){
memset(V, 0, sizeof(V));
for(int mm = 0; mm < m; mm++){
int a, b;
scanf("%d %d", &a, &b);
V[a].push_back(b);
V[b].push_back(a);
}
if(bfs()){printf("BICOLORABLE.\n");}
else{printf("NOT BICOLORABLE.\n");}
}
return 0;
}