poj 1129(DFS+四色定理)

之前练习二分图的时候有接触过染色法,用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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值