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());
}
}
}
原文:https://blog.51cto.com/tianyiya/2541649