UVa 208:Firetruck(DFS)

本文详细解析了UVA在线判题系统的经典算法竞赛题目,涉及无向图中从节点1到指定节点k的所有路径查找。通过排序边、并查集判断连通性和深度优先搜索算法实现路径查找,确保输出路径按字典序排列,同时对连通性进行预处理以避免超时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=144

题意:输入一个n (n20) 个结点的无向图以及某个结点k,按照字典序从小到大顺序输出从结点1到结点k的所有路径,要求结点不能重复经过。(本段摘自《算法竞赛入门经典(第2版)》)

分析:
       对输入的边先进行排序,然后进行DFS,这样可以保证路径是符合字典序的。要注意的是,首先要对结点1到结点k是否连通进行判断,否则会超时。连通性判断可以用并查集来实现。

代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>

using namespace std;

const int maxn = 20 + 1, INF = 1e8;

int e, ans, C, x, y;
int v[maxn], f[maxn], path[maxn];
vector< int > vec[maxn];

int Find(int x)
{
    if (f[x] != x)
        f[x] = Find(f[x]);
    return f[x];
}

void DFS(int x, int deep)
{
    if (x == e)
    {
        ++ans;
        for (int i = 0; i < deep; ++i)
            if (i < deep - 1)
                printf("%d ", path[i]);
            else
                printf("%d\n", path[i]);
        return;
    }
    int l = vec[x].size();
    for (int i = 0; i < l; ++i)
    {
        if (!v[vec[x][i]])
        {
            v[vec[x][i]] = 1;
            path[deep] = vec[x][i];
            DFS(vec[x][i], deep + 1);
            v[vec[x][i]] = 0;
        }
    }
}

int main()
{
    while (~scanf("%d", &e))
    {
        ans = 0;
        memset(v, 0, sizeof(v));
        for (int i = 1; i < maxn; ++i)
        {
            f[i] = i;
            vec[i].clear();
        }
        while (scanf("%d%d", &x, &y), x || y)
        {
            if (Find(x) != Find(y))
                f[f[x]] = f[y];
            vec[x].push_back(y);
            vec[y].push_back(x);
        }
        printf("CASE %d:\n", ++C);
        if (Find(1) == Find(e))
        {
            for (int i = 0; i < maxn; ++i)
                sort(vec[i].begin(), vec[i].end());
            v[1] = 1;
            path[0] = 1;
            DFS(1, 1);
        }
        printf("There are %d routes from the firestation to streetcorner %d.\n", ans, e);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值