poj 1129 Channel Allocation (四色定理)

本文介绍了一个基于四色定理的图着色问题解决方案,通过深度优先搜索算法来为图中的节点分配最少数量的颜色,确保相邻节点颜色不同。代码实现使用了C++语言,并针对POJ 1129题目进行了具体实现。

http://poj.org/problem?id=1129

四色定理

#include "stdio.h"
#include "iostream"
#include "cstring"
using namespace std;

bool g[27][27];
int color[27];

bool dfs(int nColor, int now, int n)  //nColor:所用颜色总数;now:当前待填颜色的物品的编号
{
	if(now > n)
		return true;

	for(int i = 1; i <= nColor; i++)
	{
		bool flag = true;
		color[now] = i;    //尝试颜色i
		for(int j = 1; j <= n; j++)
		{
			if(g[now][j] && color[j] == i) //相邻且着色一样时
			{
				flag = false;
				break;
			}
		}

		if(flag && dfs(nColor, now + 1, n))
			return true;
	}

	return false;
}

int main()
{
	int n, i, j;
	char str[40];
	while(scanf("%d", &n) && n)
	{
		memset(g, false, sizeof(g));
		memset(color, -1, sizeof(color));

		for(i = 1; i <= n; i++)
		{
			scanf("%s", str);
			j = 2;
			while(str[j])
			{
				g[i][str[j] - 'A' + 1] = true;
				j++;
			}
		}

		//由四色定理
		for(int nColor = 1; nColor <= 4; nColor++)
		{
			if(dfs(nColor, 0, n))
			{
				if(nColor == 1)
					cout << nColor << " channel needed."<< endl;
				else
					cout << nColor << " channels needed."<< endl;
				break;
			}
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值