图的着色

图着色问题,相邻的点颜色不同
      基础知识: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;
}
View Code

 

posted @ 2013-10-10 18:59  calmound  阅读(256)  评论(0编辑  收藏  举报