poj1129

题意:给定无向图,对点着色,使得相邻的结点颜色不同。

思路:使用DFS,尝试对这个图进行K种着色,首先把K设为1,看看有没有合适的方案,再逐渐把K提高,求出最少的着色数。

代码:

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;


#define M 26


int n, ans, color[M]; 

bool map[M][M], isFind;


bool ok(int x, int c) {   //判断是否存在相邻节点颜色相同

     for (int i = 0; i < n; i++)

        if (map[x][i] && c == color[i])

            return false;

     return true;

}


void DFS(int id, int total) {   //当前搜索到下标为id的节点,此时总共用的色彩数为total

     if (isFind) return;

     if (id >= n) { isFind = true; return; }  //当所有节点都被着色后,返回


     for (int i = 1; i <= total; i++) {//尝试对下标为id的节点染色i

         if (ok(id, i)) {

            color[id] = i;

            DFS(id+1, total);

            color[id] = 0;

         }

     }

     if (!isFind) {    //当用total种颜色无法完成时,则增加一种颜色进行着色

        ans++;

        DFS(id, total+1);

     }

}


int main()

{

    int i, j;

    char s[M];


    while (scanf ("%d", &n) && n) {

          memset (map, false, sizeof (map));

          memset (color, 0, sizeof (color));

          for (i = 0; i < n; i++) {

               scanf("%s",s);

               for (j = 2; s[j] != '\0'; j++)

                   map[s[0]-'A'][s[j]-'A'] = true;

          }

          isFind = false;

          ans = 1;

          DFS(0, 1);

          if (ans == 1)

              printf ("1 channel needed.\n");

          else printf ("%d channels needed.\n", ans);

    }

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值