ZOJ 1084 Channel Allocation (回溯)

这篇博客讨论了如何利用回溯法解决ZOJ 1084题目中关于频道分配的问题,该问题实质上是一个图的着色问题,需要将一个图的节点用N种颜色进行区分,确保相邻节点颜色不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1084

要解决此问题,可以先解决该问题的子问题:如何用N种颜色将Graph区分开(着色问题)。

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

#define MAX_V 26

bool IsValid(bool graph[MAX_V][MAX_V], int color[], int vIndex)
{
	for (int i = 0; i < vIndex; i++)
		if (graph[vIndex][i] == true) // have an edge
			if (color[i] == color[vIndex]) // with the same color
				return false;
	return true;
}

bool NColoring(bool graph[MAX_V][MAX_V], int vNum, int nColors)
{
	int color[MAX_V];
	memset(color, 0, sizeof(color));
	int vIndex = 0;
	while (true)
	{
		if (color[vIndex] > nColors)
		{
			if (vIndex == 0) // first vertex
				return false;
			color[vIndex] = 0;
			vIndex--;
		}
		else
		{
			color[vIndex]++;
			if (color[vIndex] <= nColors && IsValid(graph, color, vIndex))
			{
				vIndex++; // next vertex
				if (vIndex >= vNum)
					return true;
			}
		}
	}
}

int main()
{
	int n;
	bool graph[MAX_V][MAX_V];
	char line[30];
	while (cin >> n && n > 0)
	{
		memset(graph, false, sizeof(graph));
		for (int i = 0; i < n; i++)
		{
			cin >> line;
			if (strlen(line) > 2)
			{
				int vIndex = line[0] - 'A';
				for (int j = 2; j < strlen(line); j++)
					graph[vIndex][line[j] - 'A'] = true;
			}
		}
		for (int i = 1; ; i++)
			if (NColoring(graph, n, i))
			{
				if (i == 1)
					printf("1 channel needed.\n");
				else
					printf("%d channels needed.\n", i);
				break;
			}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值