首页 > 其他 > 详细

二分图(染色法)

时间:2020-10-13 21:17:31      阅读:33      评论:0      收藏:0      [点我收藏+]
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!