AcWing 860. 染色法判定二分图-java-基于bfs实现
原题链接
简单
作者:
Astarion
,
2021-02-17 21:44:48
,
所有人可见
,
阅读 309
import java.io.*;
import java.util.Arrays;
class Main {
//稀疏图,邻接表
static int n, m, idx;
static int[] h = new int[100010];
static int[] e = new int[200010];
static int[] ne = new int[200010];
static {
Arrays.fill(h, -1);
}
//记录点属于的集合
//1:左半部; 2:右半部
static int[] ce = new int[100010];
//bfs队列
static int[] queue = new int[100010];
static int head, tail;
static void insert(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
static boolean bfs(int a, int c) {
queue[tail++] = a;
ce[a] = c;
while (head < tail) {
int t = queue[head++];
int color = ce[t];
for (int i = h[t]; i != -1; i = ne[i]) {
int next = e[i];
if (ce[next] == 0) {
ce[next] = 3 - color;
queue[tail++] = next;
} else if (ce[next] == 3 - color) continue;
else return false;
}
}
return true;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
for (int i = 1; i <= m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
insert(a, b);
insert(b, a);
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
//遍历所有连通块
boolean flag = true;
for (int i = 1; i <= n; i++) {
if (ce[i] == 0 && !bfs(i, 1)) {
flag = false;
break;
}
}
if (flag) out.write("Yes");
else out.write("No");
out.flush();
out.close();
osw.close();
}
}