zoukankan      html  css  js  c++  java
  • POJ 1129 Channel Allocation 四色定理dfs

    题目: http://poj.org/problem?id=1129

    开始没读懂题,看discuss的做法,都是循环枚举的,很麻烦。然后我就决定dfs,调试了半天终于0ms A了。

     1 #include <stdio.h>
     2 #include <string.h>
     3 bool graph[26][26], vis[26][4];
     4 int n, ans;
     5 
     6 void calc()
     7 {
     8     int cnt = 0;
     9     for(int i = 0; i < 4; i++)
    10     {
    11         for(int j = 0; j < n; j++)
    12         {
    13             if(vis[j][i])
    14             {
    15                 cnt++;
    16                 break;
    17             }
    18         }
    19     }
    20     if(cnt < ans)ans = cnt;
    21 }
    22 
    23 void dfs(int x)
    24 {
    25     if(x >= n)
    26     {
    27         calc();
    28         return;
    29     }
    30 
    31     for(int i = 0; i < 4; i++)
    32     {
    33         bool ok = 1;
    34         for(int j = 0; j < n; j++)
    35         {
    36             if((graph[j][x] && vis[j][i]) || (graph[x][j] && vis[j][i]))
    37             {
    38                 ok = 0;
    39                 break;
    40             }
    41         }
    42         if(ok)
    43         {
    44             vis[x][i] = 1;
    45             dfs(x+1);
    46             vis[x][i] = 0;
    47         }
    48     }
    49 }
    50 
    51 int main()
    52 {
    53     char s[30];
    54     while(scanf("%d", &n) != EOF && n)
    55     {
    56         ans = 0x3f3f3f3f;
    57         memset(graph, 0, sizeof(graph));
    58         memset(vis, 0, sizeof(vis));
    59         for(int i = 0; i < n; i++)
    60         {
    61             scanf("%s", s);
    62             for(int j = 2; s[j]; j++)
    63             {
    64                 graph[i][s[j]-'A'] = 1;
    65             }
    66         }
    67         vis[0][0] = 1;
    68         dfs(1);
    69         if(ans == 1)
    70             printf("1 channel needed.
    ");
    71         else printf("%d channels needed.
    ", ans);
    72     }
    73     return 0;
    74 }
    View Code
  • 相关阅读:
    谦卑
    自尊和自我效能
    二手时间读书笔记
    vim学习4
    vim学习3
    hdu 5122 K.Bro Sorting
    hdu 5113 Black And White
    poj 2479 Maximum sum
    poj 2392 Space Elevator
    poj 3666 Making the Grade
  • 原文地址:https://www.cnblogs.com/wolfred7464/p/3269498.html
Copyright © 2011-2022 走看看