Here you are asked to solve a simpler similar problem. Youhave to decide whether a given arbitrary connected graph can be bicolored.That is, if one can assign colors (from a palette of two) to the nodes in sucha way that no two adjacent nodes have the same color. To simplify the problemyou can assume:
An input with n = 0 will mark the end of the input and isnot to be processed.
3 3 0 1 1 2 2 0 9 8 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0
NOT BICOLORABLE. BICOLORABLE.
题目大意:二染色。
条件:
1、不存在环
2、图是连通图
3、双向图
解题思路(转):
任意取一个点进行染色,如果发现要涂某一块时这个块已经被涂了色,并且与我们要使用的颜色不同的话,就说明这个图不能被染成BICOLORABLE的。
(1)如果没有染色,将它染色,并将它周围的点变成相反色。
(2)如果已经染色,判断是否与现在染色的点的颜色相同,相同,则退出,否则继续。
#include<stdio.h> #include<string.h> int G[205][205], vis[205], color[205]; int m, n; int DFS(int a) { for (int i = 0; i < m; i++) { if (G[a][i]) { if (!vis[i]) { vis[i] = 1; color[i] = !color[a]; DFS(i); } else if (color[i] == color[a]) return 0; } } return 1; } int main() { while (scanf("%d\n%d", &m, &n) == 2) { memset(G, 0, sizeof(G)); memset(vis, 0, sizeof(vis)); int a, b; for (int i = 0; i < n; i++) { scanf("%d %d\n", &a, &b); G[a][b] = G[b][a] = 1; } color[0] = 1; vis[0] = 1; if (DFS(0)) printf("BICOLORABLE.\n"); else printf("NOT BICOLORABLE.\n"); } return 0; }
原文地址:http://blog.csdn.net/llx523113241/article/details/43197551