zoukankan      html  css  js  c++  java
  • 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:
    ", 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.
    ", ans, n);
        }
    
    }
    #
  • 相关阅读:
    计算机的基本存储单位
    挖坑
    HEOI2017 游记
    bzoj4815 [Cqoi2017]小Q的表格
    bzoj4817 [Sdoi2017]树点涂色
    hdu5824 graph
    4.5&4.7联考题解
    高飞
    无题
    51Nod 算法马拉松23 开黑记
  • 原文地址:https://www.cnblogs.com/ruthank/p/8712058.html
Copyright © 2011-2022 走看看