UVA 208

来源:互联网 发布:linux zip 解压乱码 编辑:程序博客网 时间:2024/06/08 10:36

题目大意:输出从1走到n的所有方式。给出了不同数字之间存在道路可以走,给的数字可能超过n。

解题思路:dfs+bfs。单独用dfs来找路的话会超时,需要bfs来剪枝。剪纸的方式为,从n开始找所有连通的标记一下。题目样例给的格式是假的。。。其实路径的一行之间输,每两个号之间一个空格。

ac代码:

#include <iostream>#include <cstring>#include <queue>using namespace std;queue <int>qu;int n, t1, t2, G[1005][1005], sum, a[1005], vis[1005], cnt=1, Max;void dfs(int u, int cur){if (u == n){for (int i=0; i<cur; i++)printf(i==cur-1?"%d\n":"%d ", a[i]);sum++;}elsefor (int v=2; v<=Max; v++)if (!vis[v] && G[u][v]){vis[v] = 1;a[cur] = v;dfs(v, cur+1);vis[v] = 0;}} void bfs(){int temp;while (!qu.empty())qu.pop();qu.push(n);while (!qu.empty()){temp = qu.front();qu.pop();vis[temp] = 0;for (int i=1; i<=Max; i++)if (G[temp][i] && vis[i])qu.push(i);}}int main(){while (scanf("%d", &n) != EOF){sum = 0;memset(G, 0, sizeof(G));memset(vis, 1, sizeof(vis));Max = n;while (1){scanf("%d%d", &t1, &t2);if (!t1 && !t2)break;G[t1][t2] = G[t2][t1] = 1;Max = max(Max, max(t1, t2));}printf("CASE %d:\n", cnt++);vis[1] = 1, a[0] = 1;bfs();dfs(1, 1);printf("There are %d routes from the firestation to streetcorner %d.\n", sum, n);} return 0;}