poj 1129(dfs+图的四色定理)

时间:2023-03-10 07:07:17
poj 1129(dfs+图的四色定理)

题目链接:http://poj.org/problem?id=1129

思路:根据图的四色定理,最多四种颜色就能满足题意,使得相邻的两部分颜色不同。而最多又只有26个点,因此直接dfs即可。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std; bool map[][];
int mark[];
char str[];
int n,ans; bool Judge(int x,int color)
{
for(int i=;i<n;i++){
if(i!=x&&map[x][i]&&mark[i]==color)
return ;
}
return ;
} void dfs(int pos)
{
if(pos==n){
ans=min(ans,*max_element(mark,mark+n));
return ;
}
for(int i=pos;i<n;i++){
for(int j=;j<=;j++){
if(Judge(i,j)){
mark[i]=j;
dfs(i+);
}
}
}
} int main()
{
while(~scanf("%d",&n)&&n){
memset(map,false,sizeof(map));
for(int i=;i<n;i++){
scanf("%s",str);
for(int j=;j<strlen(str);j++){
map[i][str[j]-'A']=true;
map[str[j]-'A'][i]=true;
}
}
memset(mark,,sizeof(mark));
ans=;
mark[]=;
dfs();
if(ans==){
printf("1 channel needed.\n");
}else
printf("%d channels needed.\n",ans);
}
return ;
}