题目传送门: https://www.acwing.com/problem/content/862/
思路:
1. 对任意一未染色的顶点染色,用color数组存储颜色(color[i] = 1/2)。
2. 判断该点相邻的顶点中,是否存在未染色的点,如果还没有染色就将其染上与当前点不同的颜色;
3. 如果已经染色且颜色和相邻顶点的颜色相同则说明出现冲突,显然不是二分图;
以下分别为BFS和DFS解法:
BFS:
//Author 荣荣
//Time 2023.10.31 11:04
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010 * 2;
int n,m,ind,h[N],e[N],nex[N],color[N];
void add(int a, int b){
e[ind] = b, nex[ind] = h[a], h[a] = ind ++;
}
bool bfs(int u,int c){
queue<int> q;
color[u] = c;
q.push(u);
while (!q.empty()){
int top = q.front(); q.pop();
for (int i = h[top]; ~i; i = nex[i]){
int j = e[i];
if (color[j] != 0 && color[j] == color[top]) return false;
if (color[j] == 0){
color[j] = 3 - color[top];
q.push(j);
}
}
}
return true;
}
int main()
{
ios::sync_with_stdio(false);
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i ++){
int u,v; cin >> u >> v;
add(u,v); add(v,u);
}
for (int i = 1; i <= n; i ++){
if (color[i]) continue;
if (!bfs(i, 1)){
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}
DFS:
//Author 荣荣
//Time 2023.10.31 11:05
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010 * 2;
int n,m,ind,h[N],e[N],nex[N],color[N];
void add(int a, int b){
e[ind] = b, nex[ind] = h[a], h[a] = ind ++;
}
bool dfs(int u, int c){
color[u] = c;
for (int i = h[u]; ~i; i = nex[i]){
int j = e[i];
if (color[j] && color[j] != 3 - c) return false;
if (!color[j] && !dfs(j, 3 - c)) return false;
}
return true;
}
int main()
{
ios::sync_with_stdio(false);
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i ++){
int u,v; cin >> u >> v;
add(u,v); add(v,u);
}
for (int i = 1; i <= n; i ++){
if (color[i]) continue;
if (!dfs(i, 1)){
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}