JOJ 1003 Channel Allocation

来源:互联网 发布:网络快车加 编辑:程序博客网 时间:2024/05/21 05:55

题目:http://acm.jlu.edu.cn/joj/showproblem.php?pid=1003

图的着色问题。因为已知任何平面图都可以用不多于四种的颜色进行着色,并且使相邻顶点的颜色不同。所以分别使用1,2,3,4四种颜色进行试探。使用回溯法,代码如下:

  1. #include <stdio.h>
  2. #include <string.h>
  3. int repeaters,net[26][26],l,c,i,j,color,s[26];
  4. bool colorMap(int net[26][26],int count) {
  5.     memset(s, 0, sizeof(s));
  6.     s[0] = 1; 
  7.     int i = 1,j = 1,c;
  8.     while(i < repeaters) {
  9.         while(i >= 0 && j <= count && i < repeaters) {
  10.             for(c = 0; c < i; c++)
  11.                 if(s[c] * net[i][c] == j) break;
  12.             if(c < i) j++;
  13.             else {s[i] = j;i++;j = 1;}
  14.             if(j > count) {
  15.                 while(i >= 0 && j > count) { //多次回溯
  16.                     i--; j = s[i] + 1;
  17.                 }
  18.             }
  19.         }
  20.         if(i < 0 ) return false;
  21.     }
  22.     return true;
  23. }
  24. int main() {
  25.     char from,to;
  26.     while(scanf("%d", &repeaters), repeaters) {
  27.         memset(net, 0, sizeof(net));    
  28.         for(i = 0; i < repeaters; i++) {
  29.             if((from = getchar())  == '/n') from = getchar();
  30.             l = (int)(from - 'A');
  31.             while((to = getchar()) != '/n') {
  32.                 if(to == ':'continue;
  33.                 c = (int)(to - 'A');
  34.                 net[l][c] = 1;
  35.             }
  36.         }
  37.         for(i = 1; i <= 4; i++) {
  38.             if(colorMap(net, i)) {color = i; break;}
  39.         }
  40.         if(color == 1)
  41.             printf("1 channel needed./n");
  42.         else
  43.         printf("%d channels needed./n", color);
  44.                     
  45.     }
  46.     return 0;
  47. }   

其中,全局变量net[26][26]是图的邻接矩阵,net[i][j]值为1表示顶点i与顶点j相邻。全局变量s数组表示顶点所用的颜色。colorMap函数表示使用count种颜色对图进行试探着色,如果试探成功,则返回1,否则返回0。全局变量repeaters表示顶点数目。