您的位置:首页 > 其它

UVa 208:Firetruck(DFS)

2015-09-11 16:02 477 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=144

题意:输入一个n(n≤20)(n \le 20)个结点的无向图以及某个结点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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: