HDU - 1878 - 欧拉回路(欧拉回路)

题目链接
  如果存在欧拉回路,则需要所有点都是连通的,同时,因为题中的边没有方向,所以只要在连通的基础上判断是否有所有点的度数为偶数即可。
1.用dfs判断能否访问所有的点。

const int maxn = 1e3+10;
int degree[maxn], g[maxn][maxn], n, m;
void dfs(int u) {
    for (int i = 1; i<=n; ++i)
        if (g[u][i]) {
            --g[u][i], --g[i][u];
            dfs(i);
        }
}
int main(void) {
    while(~scanf("%d", &n) && n) {
        scanf("%d", &m);
        while(m--) {
            int a, b;
            scanf("%d%d", &a, &b);
            ++g[a][b], ++g[b][a];
            ++degree[a], ++degree[b];
        }
        dfs(1);
        bool ok = true;
        for (int i = 1; i<=n; ++i)
            for (int j = 1; j<=n; ++j) {
                if (g[i][j]) ok = false;
                g[i][j] = 0;
            }
        for (int i = 1; i<=n; ++i) 
            if (degree[i]&1) ok = false;
        printf(ok ? "1\n" : "0\n");
        zero(degree);
    }
    return 0;
}

2.用并查集来判断形成的图的个数

const int maxn = 1e3+10;
int m, n, p[maxn], degree[maxn];
int find(int root) {
    int son = root, tmp;
    while(root != p[root]) root = p[root];
    while(son != root) {
        tmp = p[son];
        p[son] = root;
        son = tmp;
    }
    return root;
}
void merge(int a, int b) {
    p[find(a)] = find(b);
}
int main(void) {
    while(~scanf("%d", &n) && n) {
        for (int i = 1; i<=n; ++i) p[i] = i, degree[i] = 0;
        scanf("%d", &m);
        while(m--) {
            int a, b;
            scanf("%d%d", &a, &b);
            merge(a, b);
            ++degree[a], ++degree[b];
        }
        int cnt = 0; bool ok = true;
        for (int i = 1; i<=n; ++i) {
            if (p[i]==i) ++cnt;
            if (degree[i]&1) ok = false;
        }
        printf(ok && cnt == 1 ? "1\n" : "0\n");
    }
    return 0;
}
posted @ 2020-04-06 13:27  shuitiangong  阅读(117)  评论(0编辑  收藏  举报