首页 > 代码库 > UVA - 208 Firetruck(消防车)(并查集+回溯)
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(消防车)(并查集+回溯)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。