一开始用连通做的,后来学习了一下白书上的并查集写法过的,用并查集挺简单的,很好过,学习一波,代码写的不好,以后还要多多努力
题目很简单。我的博客里面还有用连通过的方法,都可以作为参考
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int maxn = 21 + 4;
int par[maxn],ran[maxn];//par 表示x的父节点
int m,n;
int N,cnt;
int g[maxn][maxn];
int vis[maxn];
int a[maxn];
void init(int n)
{
for (int i = 0; i <= n; i++)
{
par[i] = i, ran[i] = 0;
}
}
int seek(int x)
{
if (par[x] == x) return x;
else return par[x] = seek(par[x]);
}
void unite(int x, int y)
{
x = seek(x), y = seek(y);
if (x == y) return;
if (ran[x] == ran[y]) par[x] = y;
else
{
par[y] = x;
if (ran[x] == ran[y]) ran[x]++;
}
}
void dfs(int k)
{
vis[1] = 1;
if(a[k] == N)
{
cnt++;
for(int i = 0; i <= k; i++)
{
if(i)
cout<<" ";
cout<<a[i];
}
cout<<endl;
return;
}
else
{
for(int i = 1; i < maxn; i++)
{
if(g[a[k]][i] && seek(a[k]) == seek(i) && !vis[i])
{
a[k + 1] = i;
vis[i] = 1;
dfs(k + 1);
vis[i] = 0;
}
}
return;
}
}
int main()
{
int num = 0;
while(scanf("%d",&N) != EOF)
{
init(maxn);
memset(g,0,sizeof(g));
memset(vis,0,sizeof(vis));
while(scanf("%d%d",&m,&n) )
{
if(m == 0 && n == 0)
break;
else
{
g[m][n] = g[n][m] = 1;
if (seek(m) != seek(n))
{
unite(m, n);
}
}
}
vis[1] = 1;
a[0] = 1;
cnt = 0;
cout<<"CASE "<<++num<<":"<<endl;
if(seek(1) == seek(N))
{
dfs(0);
cout<<"There are "<<cnt<<" routes from the firestation to streetcorner "<<N<<"."<<endl;
}
else
{
cout<<"There are "<<cnt<<" routes from the firestation to streetcorner "<<N<<"."<<endl;
}
}
return 0;
}