二分图的判定(模板)
采用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;
}