标签:list station memset 事先 题意 font map std mod
题意:输入着火点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(消防车)(并查集+回溯)
标签:list station memset 事先 题意 font map std mod
原文地址:http://www.cnblogs.com/tyty-Somnuspoppy/p/6289716.html