题意:输入着火点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[] = {, , -, , -, -, , };
const int dc[] = {-, , , , -, , -, };
const int MOD = 1e9 + ;
const double pi = acos(-1.0);
const double eps = 1e-;
const int MAXN = + ;
const int MAXT = + ;
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 = ; i <= cur; ++i){
if(i != ) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
}
else{
for(int i = ; i <= ; ++i){
if(pic[ans[cur]][i] && !vis[i]){
vis[i] = ;
ans[cur + ] = i;
dfs(cur + );
vis[i] = ;
}
}
}
}
int main(){
int kase = ;
while(scanf("%d", &n) == ){
int x, y;
memset(pic, , sizeof pic);
memset(vis, , sizeof vis);
memset(ans, , sizeof ans);
cnt = ;
for(int i = ; i < MAXN; ++i){
fa[i] = i;
}
while(scanf("%d%d", &x, &y) == ){
if(!x && !y) break;
pic[x][y] = ;
pic[y][x] = ;
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) != ){
printf("There are 0 routes from the firestation to streetcorner %d.\n", n);
continue;
}
vis[] = ;
ans[] = ;
dfs();
printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, n);
}
return ;
}