import java.util.Scanner;
public class Main {
private static int index = 0;
private static int[] lastEdge;
private static int[] end;
private static int[] previousEdge;
private static int[] color;
private static int n;
private static int m;
private static void addEdge(int a, int b) {
index++;
end[index] = b;
previousEdge[index] = lastEdge[a];
lastEdge[a] = index;
}
private static void init(int n, int m) {
Main.n = n;
Main.m = m;
Main.index = 0;
end = new int[2 * m + 1];
lastEdge = new int[n + 1];
previousEdge = new int[2 * m + 1];
color = new int[n + 1];
}
private static boolean dfs(int x, int c) {
color[x] = c;
for (int edge = lastEdge[x]; edge != 0; edge = previousEdge[edge]) {
int b = end[edge];
if (color[b] == 0) {
if (! dfs(b, 3 - c)) {
return false;
}
} else if (color[b] == c) {
return false;
}
}
return true;
}
private static boolean isBipartiteGraph() {
boolean flag = true;
for (int i = 1;i <= n; ++ i) {
if (color[i] == 0) {
if (! dfs(i, 1)) {
flag = false;
break;
}
}
}
return flag;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int m = in.nextInt();
init(n, m);
while (m -- > 0) {
int a = in.nextInt();
int b = in.nextInt();
addEdge(a, b);
addEdge(b, a);
}
System.out.println(isBipartiteGraph());
}
}
}
二分图(染色法)
转载
心之所向,素履以往 生如逆旅,一苇以航
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:二分图(匈牙利算法)
下一篇:SPFA
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章