我是靠谱客的博主 激情荷花,这篇文章主要介绍节点着色问题,现在分享给大家,希望可以做个参考。

1.问题
图的m着色问题。给定无向连通图G和m种颜色,用这些颜色给图的顶点着色,每个
顶点一种颜色。如果要求G的每条边的两个顶点着不同颜色。给出所有可能的着色方
案;如果不存在,则回答“NO”。

2.解析
(1)通过回溯的方法,不断的为每一个节点着色,在前面节点都合法的着色之后,开始对当前节点进行着色;
(2)这时候枚举可用的m个颜色,通过和前一个节点相邻的节点的颜色对比,来判断这个颜色是否合法;
(3)如果找到那么一种颜色使得当前节点能够着色,那么说明m种颜色的方案在当前是可行的。
(4)节点每次迭代加1,当节点数增加到n并且可以满足天色要求,说明m种颜色是可满足的。
3.设计
Dfs来每次确定一个点的颜色,直到确定图所有点的颜色。用mp[x][y] 来表示两点之间的关系和颜色,mp[x][y]=-1表示x、y两点无连接;mp[x][y]=0表示y点没有确定颜色;mp[x][y]=k表示y点颜色为k。

4.分析
O(n^2)的代码问题
5.源码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<map> #include<stdlib.h> #include<iostream> #include<vector> #include<string> #include<algorithm> #include<cstring> #include<queue> #include<stack> #include<cmath> #include<string> #include<cstdio> #include <iomanip> using namespace std; //const int maxn = 3e5 + 10; #define ll long long int i, j, k; int n, m; const int inf = 0x3f3f3f; const int mod = 1e9 + 7; map<ll, ll> mpp[30]; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); } const int maxn = 1010; int mp[maxn][maxn]; int ans = 0; void dfs(int t) { if (t > n) { ans++; return; } for (int i = 1; i <= m; i++) { bool flag = 1; for (int j = 1; j <= n; j++) { if (mp[t][j] != -1 && i == mp[t][j]) { flag = 0; break; } } if (flag) { for (int j = 1; j <= n; j++) { if (mp[t][j] != -1 && j != t) { mp[j][t] = i; } } dfs(t + 1); for (int j = 1; j <= n; j++) { if (mp[t][j] != -1 && j != t) { mp[j][t] = 0; } } } } } int main() { scanf("%d%d%d", &n, &k, &m);//表示给定的图有n个顶点和k条边,m种颜色。 int x, y; memset(mp, -1, sizeof mp); for (i = 0; i < k; i++) { scanf("%d%d", &x, &y); mp[x][y] = 0; mp[y][x] = 0; } dfs(1); if (ans==0) printf("NOn"); else printf("%dn", ans); return 0; } /* 5 8 4 1 2 1 3 1 4 2 3 2 4 2 5 3 4 4 5*/

Github:
https://github.com/myycjw/mcolor
代码解读及食用方法:
已放在源代码注释内

最后

以上就是激情荷花最近收集整理的关于节点着色问题的全部内容,更多相关节点着色问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(113)

评论列表共有 0 条评论

立即
投稿
返回
顶部