SDUT OJ 数据结构实验之图论八:欧拉回路

数据结构实验之图论八:欧拉回路

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

在哥尼斯堡的一个公园里,有七座桥将普雷格尔河中两个岛及岛与河岸连接起来。



能否走过这样的七座桥,并且每桥只走一次?瑞士数学家欧拉最终解决了这个问题并由此创立了拓扑学。欧拉通过对七桥问题的研究,不仅圆满地回答了哥尼斯堡七桥问题,并证明了更为广泛的有关一笔画的三条结论,人们通常称之为欧拉定理。对于一个连通图,通常把从某结点出发一笔画成所经过的路线叫做欧拉路。人们又通常把一笔画成回到出发点的欧拉路叫做欧拉回路。具有欧拉回路的图叫做欧拉图。

你的任务是:对于给定的一组无向图数据,判断其是否成其为欧拉图?

Input

连续T组数据输入,每组数据第一行给出两个正整数,分别表示结点数目N(1 < N <= 1000)和边数M;随后M行对应M条边,每行给出两个正整数,分别表示该边连通的两个结点的编号,结点从1~N编号。 

Output

若为欧拉图输出1,否则输出0。

Sample Input

1
6 10
1 2
2 3
3 1
4 5
5 6
6 4
1 4
1 6
3 4
3 6

Sample Output

1

欧拉回路基本算法就是进行深搜,但是很有可能只访问了图的一部分而提前返回起点,如果从起点出发的所有边均已用完,那么图中就会有部分遍历不到。最容易的补救方法就是找出有尚未访问的边的路径上的第一个顶点,并执行一次深度优先搜索,这将给出另外一个回路,把它拼接到原来的回路上。继续该过程直到所有的边都被遍历到为止。

然鹅,此题仅仅让你判断,并查集就可以轻松解决,度数都为偶数且在一个集合里

#include <iostream>
using namespace std;


typedef int ElementType;
typedef struct
{
    ElementType Data;
    int Parent;
}SetType;

SetType S[10001];
int MaxSize;

int Find ( SetType *S, ElementType X )
{
    int i = 0;
    while( i<MaxSize && S[i].Data != X )
        i++;
    while( S[i].Parent >= 0 )
        i = S[i].Parent ;
    return i;
}

void Union ( SetType *S, ElementType X1, ElementType X2 )
{
    int Root1, Root2;
    Root1 = Find ( S, X1 );
    Root2 = Find ( S, X2 );
    if( Root1 != Root2 )
        S[Root2].Parent = Root1;
}

int sum[10001];

int main()
{
    int t;
    cin >> t;
    while ( t-- )
    {
        int num = 0;
        int n, m, i;
        cin >> n >> m;
        for( i=1; i<=n; i++ )
        {
            S[i].Parent = -1;
            S[i].Data   =  i;
        }
        MaxSize = n;
        for( i=0; i<m; i++ )
        {
            int a, b;
            cin >> a >> b;
            Union( S, a, b );
            sum[a]++;
            sum[b]++;
        }
        for( i=0; i<n; i++ )
        {
            if(S[i].Parent == -1)
                num++;
        }
        int flag = 1;
        for( i=0; i<n; i++ )
            if(sum[i] % 2 == 1)
            {
                flag = 0;
                break;
            }
        if( num == 1 && flag == 1 )
            cout << 1 << endl;
        else
            cout << 0 << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/winner647520/article/details/81346647