UVa-208 Firetruck (图的DFS)

UVA-208

天道好轮回。UVA饶过谁。

就是一个图的DFS。

不过这个图的边太多,要事先判一下起点和终点是否联通(我喜欢用并查集),否则会TLE。

 

 

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#define maxn 40
using namespace std;

int a[maxn][maxn], vis[maxn], ans, f[maxn];
vector<int> q;

int build(int x, int y)
{
    a[x][y] = 1;
    a[y][x] = 1;
}

int found(int x)
{
    if (f[x] == x) return x;
    f[x] = found(f[x]);
    return f[x];

}

int add(int x, int y)
{
    int fx = found(x), fy = found(y);
    if (fx != fy) f[fx] = fy;
}

void DFS(int k, int n)
{
    if (k == n)
    {
        for (int i = 0; i < q.size()-1; i++)
            cout << q[i] << " ";
        cout << q[q.size()-1] << endl;
        ans++;
    }

    for (int  i = 1; i <= maxn / 2; i++)
        if (!vis[i] && a[k][i])
        {
            vis[i] = 1;
            q.push_back(i);
            DFS(i, n);
            q.pop_back();
            vis[i] = 0;
        }
}

int main()
{
    int n, cases = 0;
    while (cin >> n)
    {
        memset(a, 0, sizeof(a));
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= maxn/2; i++) f[i] = i;
        ans = 0;
        while (!q.empty()) q.pop_back();
        int x, y;
        while (cin >> x >> y && x && y)
        {
            build(x, y);
            add(x, y);
        }
        ++cases;
        printf("CASE %d:\n", cases);
        q.push_back(1);
        vis[1] = 1;
        if (found(1) == found(n)) DFS(1, n);
        printf("There are %d routes from the firestation to streetcorner %d.\n", ans, n);
    }

}
#

 

 

posted @ 2017-12-14 18:13  jvruodejrLS  阅读(121)  评论(0编辑  收藏  举报

Contact with me