UVA10054 The Necklace 无向图欧拉回路+连通性

来源:互联网 发布:gymnopedie no.1 知乎 编辑:程序博客网 时间:2024/05/16 00:59

很基础的一道题,主要是学习一下如何使用并查集判断图的连通性以及无向图欧拉回路的判断

还有就是最重点的欧拉回路的输出路径问题

DFS部分是重点,先遍历,后输出

#include<bits/stdc++.h>
using namespace std;
int mp[55][55];
int rudu[60];
int father[60];
void dfs(int u)
{
    for(int i=1;i<=50;i++)
        if(mp[u][i])
        {
            mp[u][i]--;mp[i][u]--;
            dfs(i);
            printf("%d %d\n", i, u);
        }
}
void init(int n)
{
    for(int i=1;i<=n;i++)
        father[i] = i;
}


int findd(int n)
{
    return father[n] == n?n:father[n] = findd(father[n]);
}
void unionn(int u,int v)
{
    father[findd(u)] = findd(v);
}
int main()
{
    int i, n, a, b, temp, t, T;
    scanf("%d", &T);
    for(temp=1;temp<=T;temp++)
    {
    memset(mp, 0,sizeof(mp));
    memset(rudu, 0, sizeof(rudu));
    init(50);
    scanf("%d", &n);
    while(n--)
    {
        scanf("%d%d", &a, &b);
        unionn(a, b);
        mp[a][b]++;mp[b][a]++;
        rudu[a]++;rudu[b]++;
    }
    printf("Case #%d\n", temp);
    t=0;
    for(i=1;i<=50;i++)
       if(rudu[i]&&father[i] == i)
            t++;
    if(t!=1)
    {
        printf("some beads may be lost\n\n");
  continue;
    }
    t=0;
    for(i=1;i<=50;i++)
        if(rudu[i]%2)
            t=1;
    if(t==1)
    {
        printf("some beads may be lost\n\n");
        continue;
    }


    dfs(a);
    printf("\n");
    }
    return 0;
}

原创粉丝点击