UVA - 208 Firetruck(消防车)(并查集+回溯)
Posted SomnusMistletoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA - 208 Firetruck(消防车)(并查集+回溯)相关的知识,希望对你有一定的参考价值。
题意:输入着火点n,求结点1到结点n的所有路径,按字典序输出,要求结点不能重复经过。
分析:用并查集事先判断结点1是否可以到达结点k,否则会超时。dfs即可。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 30 + 10; const int MAXT = 10000 + 10; using namespace std; int fa[MAXN]; int pic[MAXN][MAXN]; int vis[MAXN]; int ans[MAXN]; int cnt; int n; int Find(int v){ return fa[v] = (fa[v] == v) ? v : Find(fa[v]); } void dfs(int cur){ if(ans[cur] == n){ ++cnt; for(int i = 1; i <= cur; ++i){ if(i != 1) printf(" "); printf("%d", ans[i]); } printf("\n"); } else{ for(int i = 1; i <= 21; ++i){ if(pic[ans[cur]][i] && !vis[i]){ vis[i] = 1; ans[cur + 1] = i; dfs(cur + 1); vis[i] = 0; } } } } int main(){ int kase = 0; while(scanf("%d", &n) == 1){ int x, y; memset(pic, 0, sizeof pic); memset(vis, 0, sizeof vis); memset(ans, 0, sizeof ans); cnt = 0; for(int i = 0; i < MAXN; ++i){ fa[i] = i; } while(scanf("%d%d", &x, &y) == 2){ if(!x && !y) break; pic[x][y] = 1; pic[y][x] = 1; int tx = Find(x); int ty = Find(y); if(tx < ty) fa[ty] = tx; else if(tx > ty) fa[tx] = ty; } printf("CASE %d:\n", ++kase); if(Find(n) != 1){ printf("There are 0 routes from the firestation to streetcorner %d.\n", n); continue; } vis[1] = 1; ans[1] = 1; dfs(1); printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, n); } return 0; }
以上是关于UVA - 208 Firetruck(消防车)(并查集+回溯)的主要内容,如果未能解决你的问题,请参考以下文章