首页 > 学院 > 开发设计 > 正文

HDU1878 欧拉回路

2019-11-08 02:56:38
字体:
来源:转载
供稿:网友

问题链接: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;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表