节点着色问题

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.源码

#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("NO\n");
	else
		printf("%d\n", 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
代码解读及食用方法:
已放在源代码注释内

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值