
- 时间复杂度是 O(n+m), n表示点数,m 表示边数
模板
int n;
int h[N], e[M], ne[M], idx;
int color[N];
bool dfs(int u, int c)
{
color[u] = c;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (color[j] == -1)
{
if (!dfs(j, !c)) return false;
}
else if (color[j] == c) return false;
}
return true;
}
bool check()
{
memset(color, -1, sizeof color);
bool flag = true;
for (int i = 1; i <= n; i ++ )
if (color[i] == -1)
if (!dfs(i, 0))
{
flag = false;
break;
}
return flag;
}
public static int[] h = new int[N];
public static int[] e = new int[M];
public static int[] ne = new int[M];
public static int[] color = new int[N];
public static boolean[] check() {
Arrays.fill(color, -1);
boolean flag = true;
for (int i = 1; i <= n; i++) {
if (color[i] == -1) {
if (!dfs(i, 0)) {
flag = false;
break;
}
}
}
return flag;
}
public static boolean dfs(int u, int c) {
color[u] = c;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (color[j] == -1) {
if (!dfs(j, 1 - c)) {
return false;
}
} else if (color[j] == c) {
return false;
}
}
return true;
}
练习
01 染色法判定二分图

import java.io.*;
import java.util.Arrays;
public class Main {
public static final int N = 100010;
public static final int M = N * 2;
public static int[] h = new int[N];
public static int[] e = new int[M];
public static int[] ne = new int[M];
public static int[] color = new int[N];
public static int n, m, idx;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
String[] str1 = br.readLine().split(" ");
n = Integer.parseInt(str1[0]);
m = Integer.parseInt(str1[1]);
Arrays.fill(h, -1);
idx = 0;
while (m-- > 0) {
String[] str2 = br.readLine().split(" ");
int u = Integer.parseInt(str2[0]);
int v = Integer.parseInt(str2[1]);
add(u, v);
add(v, u);
}
if (check()) {
pw.println("Yes");
} else {
pw.println("No");
}
br.close();
pw.close();
}
public static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
public static boolean check() {
Arrays.fill(color, -1);
boolean flag = true;
for (int i = 1; i <= n; i++) {
if (color[i] == -1) {
if (!dfs(i, 0)) {
flag = false;
break;
}
}
}
return flag;
}
public static boolean dfs(int u, int c) {
color[u] = c;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (color[j] == -1) {
if (!dfs(j, 1 - c)) {
return false;
}
} else if (color[j] == c) {
return false;
}
}
return true;
}
}