void-man

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

题目大意,给出几个信号站的相连关系,任意两个相连的信号站不能用一个channel,问最终至少用几个channel可以让所有信号站发新号

这个是经典的四可着色定理,用dfs来暴力搜索,每次选定一个颜色后依次往下dfs直到所有的顶点都满足

PS:唉dfs的题目,每次看着答案感觉特别有感觉,但是自己写的时候总不知道如何下手,多练习吧

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
bool map[26][26];
int n;
int color[26];
int color_index;
int min_color;
bool isOk(int depth, int clr)
{
    for(int i=0; i<n; i++)
    {
        if(map[depth][i] && color[i]==clr)
        {
            return false;
        }
    }
    return true;
}

void DFS(int depth)
{
    if(color_index>min_color)
    {
        return;
    }
    if(depth>=n)
    {
        if(min_color>color_index)
        {
            min_color=color_index;
        }
        return;
    }

    for(int k=1; k<=color_index; k++)
    {
        if(isOk(depth,k))
        {
            color[depth]=k;
            DFS(depth+1);
            color[depth]=0;
        }
    }

    color_index++;
    color[depth]=color_index;
    DFS(depth+1);
    color[depth]=0;
    color_index--;

}

int main()
{
    char temp[32];

    while(scanf("%d",&n) && n)
    {
        memset(map,0,sizeof(map));
        memset(color,0,sizeof(color));
        color_index=1;
        min_color=99999;
        for(int i=0; i<n; i++)
        {
            scanf("%s",temp);
            for(int j=2; temp[j]!='\0'; j++)
            {
                map[i][temp[j]-'A']=true;
            }
        }
        DFS(0);
        if(min_color==1)
            printf("%d channel needed.\n",min_color);
        else
            printf("%d channels needed.\n",min_color);
    }
    return 0;
}
posted on 2011-06-02 22:29  void-man  阅读(256)  评论(0)    收藏  举报