UVA 208 并查集+dfs

//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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值