图的着色问题

算法分类:

回溯


算法原理:

见《算法设计技巧与分析》 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();
	}
}


你可能感兴趣的:(c,算法,Allocation)