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