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;
}
}
}