图的着色问题

算法分类:

回溯


算法原理:

见《算法设计技巧与分析》 P219


算法时间复杂度:

最坏时间复杂度(n3^n)


代码实现:(POJ1129)

/* Author: jokes000
 * POJ 1129
 * Channel Allocation
 */

#include <iostream>
#include <string.h>
using namespace std;

int G[27][27];	// 存放各站邻接情况
int C[27];		// 存放目前个点着色情况
int n;			// 存放广播站数目
bool flag;		// 是否找出合法着色

// 深度优先搜索
// pos:为当前着色位置
// maxcolor:可着色数目
void color(int pos, int maxcolor) {
	
	for (int c = 1; c <= maxcolor; ++ c) {
		C[pos] = c;
		bool legal = true;
		// 判断着色是否合法
		for (int i = 1; i <= n; ++ i) {
			if (G[pos][i] == 1) {
				if (C[pos] == C[i]) {
					legal = false;
					break;
				}
			}
		}

		if (legal) {
			if (pos == n) {
				flag = true;
				return;
			} else {
				color(pos+1, maxcolor);
			}
		}
	}
};

void solve() {
	flag = false;
	int  maxcolor = 0;

	while (!flag) {
		++ maxcolor;
		color(1, maxcolor);
	}

	if (maxcolor == 1)
		printf("%d channel needed.\n",maxcolor);
	else
		printf("%d channels needed.\n",maxcolor);
};

int Convert(char s) {
	return s - 'A' + 1;
}

void init() {
	char in[30];

	memset(G, 0, sizeof(G));
	memset(C, 0, sizeof(C));

	for (int i = 0; i < n; ++ i) {
		scanf("%s",in);
		int s = Convert(in[0]);
		int len = strlen(in);
		for (int j = 2; j < len; ++ j) {
			int e = Convert(in[j]);
			G[s][e] = G[e][s] = 1;
		}
	}
};

int main() {

	while (scanf("%d",&n)!=EOF, n) {
		init();
		solve();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值