图着色问题,相邻的点颜色不同 基础知识:http://wenku.baidu.com/view/d7242fd1c1c708a1284a444d.html 名词解析: 平凡图:只有一个点 若图为平凡图,则其染色的点x(G)= 1 偶图:图上的点分属于两个集合s1,s2 若图为偶图X(G)= 2
POJ 1129 Channel Allocation http://poj.org/problem?id=1129 题意:n个中继器, 相邻的不能用一个通道,求最少用多少个通道。 分析:dfs+四色定理剪枝,所谓四色定理就是一个图最多用四种颜色就能够全部染色
#include<stdio.h>
#include<string.h>
const int MN=30;
int mat[MN][MN],opt[MN];
char s[MN];
int n;
//判断相邻的顶点的颜色是否相同
bool same(int cur)
{
for(int i=0;i<n;i++)
{
if(mat[i][cur] && opt[cur]==opt[i]) return true;
}
return false;
}
bool DFS(int cur,int Maxcolor)
{
if(cur==n) return true;
for(opt[cur]=1;opt[cur]<=Maxcolor;opt[cur]++)//枚举颜色
{//若相邻的颜色没有一样的,继续往下搜
if(!same(cur)) return DFS(cur+1,Maxcolor);
}
return false;
}
int main()
{
int i,j;
while(scanf("%d",&n) && n)
{
memset(mat,0,sizeof(mat));
memset(opt,0,sizeof(opt));
getchar();
for(i=1;i<=n;i++)
{
gets(s);
int x=s[0]-'A';
for(j=2;s[j];j++)
{
int y=s[j]-'A';
mat[x][y]=mat[y][x]=1;
}
}
for(i=1;i<=4;i++)
{
if(DFS(0,i)) break;
}
if(i==1) printf("1 channel needed.\n");
else printf("%d channels needed.\n",i);
}
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有