UVA - 208 Firetruck

//非常水的一道回溯题, 只是输出问题醉了, 题目里的输出不是AC的输出格式;

//预处理很重要 不然会超时!

#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=20 + 5;
int res[maxn][maxn];
int par[maxn];
int r[maxn];
int used[maxn];
vector<int> ans;
int n;
int cnt = 0;
void init()
{
    for(int i = 0; i < maxn; ++i) { par[i] = i; r[i] = 0;}
}
int f(int x)
{
    return x == par[x] ? x : par[x] = f(par[x]);
}
void unite(int x, int y)
{
    x = f(x);
    y = f(y);
    if(x==y) return ;
    if(r[x] < r[y]) par[x] = y;
    else
    {
        par[y] = x;
        if(r[x] == r[y]) ++r[x];
    }
}
void dfs(int u)
{
    if(u == n)
    {
        ++cnt;
        for(int i = 0; i < (int)ans.size(); ++i)
        {
            if(!i) cout << ans[i];
            else cout << " " << ans[i];
        }
        printf("\n");
    }
    vector<int> tmp = ans;
    for(int i = 1; i <= maxn; ++i)
    {
        if(res[u][i] && !used[i])
        {
            used[i] = 1;
            ans.push_back(i);
            dfs(i);
            ans = tmp;
            used[i] = 0;
        }
    }
}
int main()
{
    int kase = 0;
    while(scanf("%d", &n) == 1)
    {
        init();
        cnt = 0;
        memset(res,0,sizeof(res));
        memset(used,0,sizeof(used));
        ans.clear();
        int u, v;
        while(scanf("%d%d", &u, &v)== 2)
        {
            if(u == 0 && v == 0) break;
            res[u][v] = 1;
            res[v][u] = 1;
            unite(u, v);
        }
        printf("CASE %d:\n", ++kase);
        if(f(1) != f(n)) { printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, n); continue;}
        ans.push_back(1);
        used[1] = 1;
        dfs(1);
        printf("There are %d routes from the firestation to streetcorner %d.\n", cnt, n);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值