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

来源:互联网 发布:英语课上配音软件 编辑:程序博客网 时间:2024/06/06 18:51

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss

Problem Description

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



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

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

Input

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

Output

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

Example Input

16 101 22 33 14 55 66 41 41 63 43 6

Example Output

1

Hint

如果无向图连通并且所有结点的度都是偶数,则存在欧拉回路,否则不存在。 

Author


方法一:并查集
#include<bits/stdc++.h>using namespace std;int n, m, a[1010], dis[1010], num;struct st{    int a, b;}s[1010];int Find(int x){    return dis[x] == x ? x : Find(dis[x]);}int kruskal(){    int x, y, i;    for(i = 1; i <= m; i++)    {        x = Find(s[i].a);        y = Find(s[i].b);        if(x!=y)        {            dis[x] = y;            num++;        }    }    if(num!=n-1) return 0;    else return 1;}int main(){    int i, t, f, k;    scanf("%d", &t);    while(t--)    {        num = 0; f = 1;        scanf("%d%d", &n, &m);        memset(a, 0, sizeof(a));        memset(dis, 0, sizeof(dis));        for(i = 1; i <= m; i++)        {            scanf("%d%d", &s[i].a, &s[i].b);            a[s[i].a]++; a[s[i].b]++;        }        for(i = 1; i <= n; i++)        {            if(a[i]%2==1)            {                f = 0;                break;            }        }        for(i = 1; i <= n; i++)            dis[i] = i;        k = kruskal();        if(f)        cout<<k<<endl;        else cout<<f<<endl;    }}

int kruskal()
{
    int x, y, i;
    for(i = 1; i <= m; i++)
    {
        x = Find(s[i].a);
        y = Find(s[i].b);
        if(x!=y)
        {
            dis[x] = y;
        }
    }
    for(i = 1; i <= n; i++)
    if(dis[i]==i) num++;
    if(num!=1) return 0;
    else return 1;
}



方法二:DFS

#include<bits/stdc++.h>using namespace std;int n, m, a[1010][1010], num;int vis[10100], s[1010];void dfs(int j){    int i;    vis[j] = 1;    num++;    for(i = 1; i <= n; i++)    {        if(a[j][i]&&(!vis[i]))        {            dfs(i);        }    }}int main(){    int i, t, x, y, f;    scanf("%d", &t);    while(t--)    {        num = 0; f = 1;        scanf("%d%d", &n, &m);        memset(a, 0, sizeof(a));        memset(vis, 0, sizeof(vis));        memset(s, 0, sizeof(s));        for(i = 0; i < m; i++)        {            scanf("%d%d", &x, &y);            a[x][y] = a[y][x] = 1;            s[x]++; s[y]++;        }        for(i = 1; i <= n; i++)        {            if(s[i]%2==1)            {                f = 0;                break;            }        }        dfs(1);        if(f&&num==n)        cout<<f<<endl;        else cout<<"0"<<endl;    }}

方法三:BFS(此处略去50行代码)

原创粉丝点击