并查集的使用例题uva208

一开始用连通做的,后来学习了一下白书上的并查集写法过的,用并查集挺简单的,很好过,学习一波,代码写的不好,以后还要多多努力

题目很简单。我的博客里面还有用连通过的方法,都可以作为参考

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值