• HDU1878 欧拉回路


    问题链接:HDU1878 欧拉回路

    问题简述:输入若干测试用例,判定一个无向图是否有欧拉回路。

    问题分析:无向图的欧拉回路需要满足两个条件,一是图是连通的,二是各个结点的入出度相同(有偶数个连接的边)。

    程序说明:程序中用并查集判定图是否连通,对图构造一个并查集(树)后,如果连通则其根相同。用数组degree[]统计各个结点的连通度。

    AC的C++语言程序如下:

    /* HDU1878 欧拉回路 */
    
    #include <iostream>
    #include <cstring>
    #include <vector>
    
    using namespace std;
    
    // 并查集类
    class UF {
    private:
        vector<int> v;
    public:
        UF(int n) {
            for(int i=0; i<=n; i++)
                v.push_back(i);
        }
    
        int Find(int x) {
            for(;;) {
                if(v[x] != x)
                    x = v[x];
                else
                    return x;
            }
        }
    
        bool Union(int x, int y) {
            x = Find(x);
            y = Find(y);
            if(x == y)
                return false;
            else {
                v[x] = y;
                return true;
            }
        }
    };
    
    const int MAXN = 1000;
    
    int degree[MAXN+1];
    
    int main()
    {
        int n, m, src, dest;
    
        while(cin >> n && n != 0) {
            UF uf(n);
    
            cin >> m;
    
            // 变量初始化
            memset(degree, 0, sizeof(degree));
    
            // 统计各个结点的联通度,并构建并查集(为判定图是否为连通图)
            while(m--) {
                cin >> src >> dest;
    
                degree[src]++;
                degree[dest]++;
    
                if(uf.Find(src) != uf.Find(dest))
                    uf.Union(src, dest);
            }
    
            // 判定
            int root = uf.Find(1), ans = 1;
            for(int i=1; i<=n; i++)
                if(uf.Find(i) != root || degree[i] & 1 /*degree[i] % 2 == 1*/) {
                    ans = 0;
                    break;
                }
    
            // 输出结果
            cout << ans << endl;
        }
    
        return 0;
    }


  • 相关阅读:
    Debate
    图形算法
    OpenGL Notes
    How to Write an Ethics Paper
    Thesis
    addWindowListener -> WindowAdapter -> windowClosing
    Thesis
    Bootcamp: An error occurred while partitioning the disk
    What Is XML Schema
    What Is XML
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564128.html
Copyright © 2020-2023  润新知