您的位置:首页 > 其它

poj 1129(DFS+四色定理)

2016-02-05 00:16 417 查看
之前练习二分图的时候有接触过染色法,用01染色法判断一个图是否是二分图,而这道题是进行图的染色,求最少最需要的着色数。

第一次接触到四色定理,对于任何一个无向图着色,最多只需要4种颜色即可,具体证明参考网上的资料吧,我也不太会= =!

用DFS枚举所有可能,如果贪心的话可能过不了(因为数据比较水),求出满足条件的最小着色数。

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=30;
int n;
char str[maxn];
int map[maxn][maxn];
int color[maxn],maxColor;

bool ok(int i,int k){
for(int j=0;j<n;j++)
if(j!=i&&map[i][j]&&color[j]==k)//第i个节点和第j个节点相邻且着色相同
return false;
return true;
}

void dfs(int deep){
if(deep==n){
maxColor=min(maxColor,*max_element(color,color+n));
return ;
}
for(int i=deep;i<n;i++){
for(int k=1;k<=4;k++){
if(ok(i,k)){
color[i]=k;
dfs(i+1);
}
}
}
}

int main(){
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
while(~scanf("%d",&n)&&n){
memset(map,0,sizeof(map));
for(int i=0;i<n;i++){
scanf("%s",str);
int len=strlen(str);
if(len>2){
for(int j=2;j<len;j++){
map[str[0]-'A'][str[j]-'A']=1;
map[str[j]-'A'][str[0]-'A']=1;
}
}
}
maxColor=INF;
dfs(0);
if(maxColor==1)
printf("%d channel needed.\n",maxColor);
else
printf("%d channels needed.\n",maxColor);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: