码迷,mamicode.com
首页 > 其他好文 > 详细

二分图(染色法)

时间:2020-11-12 14:07:57      阅读:8      评论:0      收藏:0      [点我收藏+]

标签:color   out   print   str   while   --   ext   tin   graph   

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()); } } }

二分图(染色法)

标签:color   out   print   str   while   --   ext   tin   graph   

原文地址:https://blog.51cto.com/tianyiya/2541649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!