uva 208 Firetruck
2013-10-28 14:42
549 查看
做简单的逆向递归优化后再正向用回溯法进行递归枚举就行了,不进行优化会超时。
#include <stdio.h> #include <vector> using namespace std; bool link_table[30][30]; bool connected[30]; bool visited[30]; vector<int> path; int path_count; void clear_link_table() { for(int i=1; i<=25; i++) { for(int j=1; j<=25; j++) link_table[i][j] = false; } } void dfs(int cur, int fire_index) { if(visited[cur]) return; if(!connected[cur]) return; visited[cur] = true; path.push_back(cur); if(cur == fire_index) { int i; for(i=0; i<path.size()-1; i++) printf("%d ", path[i]); printf("%d\n", path[i]); vector<int>::iterator it; it = path.end(); path.erase(--it); visited[cur] = false; path_count++; return; } for(int i=1; i<=25; i++) if(link_table[i][cur]) dfs(i, fire_index); vector<int>::iterator it; it = path.end(); path.erase(--it); visited[cur] = false; } void find_connected(int cur) { if(!connected[cur]) { connected[cur] = true; for(int i=1; i<=25; i++) if(link_table[i][cur]) find_connected(i); } } void func(int fire_index) { int i; for(i=1; i<=25; i++) connected[i] = false; find_connected(fire_index); for(i=1; i<=25; i++) visited[i] = false; path.clear(); path_count = 0; dfs(1, fire_index); printf("There are %d routes from the firestation to streetcorner %d.\n", path_count, fire_index); } int main(void) { int n; int a, b; int count; //freopen("input.dat", "r", stdin); count = 0; while(scanf("%d",&n) != EOF) { clear_link_table(); while(1) { scanf("%d %d", &a, &b); if(!a && !b) break; link_table[a][b] = link_table[b][a] = true; } count ++; printf("CASE %d:\n", count); func(n); } }
相关文章推荐
- uva 208 - Firetruck
- UVA 208 - Firetruck
- UVA 208 Firetruck
- UVA - 208 Firetruck
- UVa 208 Firetruck 消防车
- uva_208-Firetruck(救火车)
- Uva 208 Firetruck(dfs并查集优化)
- (UVA - 208)Firetruck(路径输出问题,回溯+并查集/floyd算法+dfs)
- UVa 208 Firetruck
- uva208 Firetruck
- UVa 208 - Firetruck
- uva 208 Firetruck
- uva 208 Firetruck (DFS + 并查集)
- UVA 208 Firetruck
- [回溯&&剪枝]Firetruck UVA208
- UVa208,Firetruck
- UVA 208 Firetruck 消防车(回溯 + 剪枝)
- UVA 208 Firetruck
- uva 208 Firetruck
- uva208 - Firetruck