码迷,mamicode.com
首页 > 其他好文 > 详细

UVa208 Firetruck (DFS)

时间:2016-09-05 12:00:00      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

链接:http://acm.hust.edu.cn/vjudge/problem/19858
分析:可以先预处理下从终点开始把能走到的结点mark下来,能节省不少时间和空间的浪费,vis标记是否走过该结点的同时,也记录经过的结点在路径上的第几步。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 const int maxn = 30;
 7 
 8 int t, cnt, num, G[maxn][maxn], vis[maxn], mark[maxn];
 9 
10 void build() {
11     memset(G, 0, sizeof(G));
12     int u, v; cnt = 1;
13     while (scanf("%d%d", &u, &v) == 2 && u) {
14         G[u][v] = 1;
15         G[v][u] = 1;
16         if (u > cnt) cnt = u;
17         if (v > cnt) cnt = v;
18     }
19 }
20 
21 void judge(int n) {
22     mark[n] = 1;
23     for (int i = 1; i <= cnt; i++)
24         if (G[n][i] && !mark[i]) judge(i);
25 }
26 
27 void print_ans() {
28     num++;
29     printf("%d", 1);
30     for (int step = 2; step <= vis[t]; step++)
31         for (int pos = 2; pos <= cnt; pos++)
32             if (vis[pos] == step) printf(" %d", pos);
33     printf("\n");
34 }
35 
36 void dfs(int u) {
37     if (u == t) print_ans();
38     else {
39         for (int v = 2; v <= cnt; v++)
40             if (G[u][v] && !vis[v] && mark[v]) {
41                 vis[v] = vis[u] + 1;
42                 dfs(v);
43                 vis[v] = 0;
44             }
45     }
46 }
47 
48 int main() {
49     int kase = 0;
50     while (scanf("%d", &t) == 1) {
51         build();
52         printf("CASE %d:\n", ++kase);
53         memset(mark, 0, sizeof(mark));
54         judge(t);
55         num = 0, vis[1] = 1;
56         dfs(1);
57         printf("There are %d routes from the firestation to streetcorner %d.\n", num, t);
58     }
59     return 0;
60 }

 

UVa208 Firetruck (DFS)

标签:

原文地址:http://www.cnblogs.com/XieWeida/p/5841661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!