POJ 1129 Channel Allocation 四色定理dfs

本文详细介绍了如何使用深度优先搜索(DFS)解决POJ在线编程比赛中的一道题目,通过枚举法优化代码实现,最终达到高效求解的目的。

题目: 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.\n");
71         else printf("%d channels needed.\n", ans);
72     }
73     return 0;
74 }
View Code

 

转载于:https://www.cnblogs.com/wolfred7464/p/3269498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值