//http://acm.hust.edu.cn/vjudge/problem/19858
//要先判断N与1是否联通,以及要搜索的点应该与N联通。
#include <stdio.h>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
#include <functional>
#include <vector>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <iostream>
#include <sstream>
#include <time.h>
#include <stack>
#include <set>
#include <map>
#include <time.h>
#include <bitset>
using namespace std;
const int MAX=25;
int N,a,b,M;
int G[MAX][MAX];
int pre[MAX];
bool used[MAX];
int Ans[MAX],Cnt;
int Find(int x)
{
int r=x;
while(r!=pre[r])
r=pre[r];
int i=x,j;
while(pre[i]!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
void mix(int x,int y)
{
int fx=Find(x),fy=Find(y);
if(fx!=fy)
pre[fy]=fx;
}
void dfs(int x,int l)
{
Ans[l]=x;
if (x==N)
{
for (int i=0;i<=l;i++)
cout<<Ans[i]<<(i==l?'\n':' ');
Cnt+=1;
return;
}
for (int i=1;i<MAX;i++)
{
if (!used[i]&&i!=x&&Find(i)==M&&G[x][i]==1)
{
used[i]=true;
dfs(i,l+1);
used[i]=false;
}
}
}
int main()
{
cin.sync_with_stdio(false);
int cases=1;
while (cin>>N)
{
for (int i=0;i<MAX;i++)
pre[i]=i;
Cnt=0;
memset(G,0,sizeof(G));
memset(used,false,sizeof(used));
memset(Ans,0,sizeof(Ans));
cout<<"CASE "<<cases++<<":\n";
while (cin>>a>>b)
{
if (a==0&&b==0)
break;
G[a][b]=G[b][a]=1;
mix(a,b);
}
if (Find(1)==Find(N))
{
M=Find(1);
used[1]=true;
dfs(1,0);
}
cout<<"There are "<<Cnt<<" routes from the firestation to streetcorner "<<N<<".\n";
}
return 0;
}
UVA 208 并查集+dfs
最新推荐文章于 2020-08-15 15:42:50 发布