欧拉回路判断

来源:互联网 发布:js 判断是不是汉字 编辑:程序博客网 时间:2024/05/11 02:29
//判断无向图是否是欧拉回路,欧拉回路:所有节点的度为偶数且连通//使用并查集判断连通性//题目:http://acm.hdu.edu.cn/showproblem.php?pid=1878#include<iostream>#include <cstdio>using namespace std;int father[1005];int Find(int i){    int t = father[i];    while(i!=father[i])    {        i = father[i];    }    father[t] = i;    return i;}void Union(int i,int j){    int f1 = Find(i);    int f2 = Find(j);    if( f1 != f2 )    {        father[f1] = f2;    }}int main(){    int n,m;    int degree[1005];       while(cin>>n &&n)    {        cin>>m;                memset(degree,0,sizeof(degree));        for(int i = 1;i<=n;i++)        {            father[i] = i;        }        int a,b;        for(int i = 0;i<m;i++)        {            scanf("%d%d",&a,&b);            degree[a]++;            degree[b]++;            Union(a,b);        }        bool flag = true;        int num = 0;        for(int i = 1;i<=n;i++)        {            if(father[i] == i)            {                num++;            }            if(num > 1)            {                flag = false;                break;            }            if(degree[i]%2!=0) //节点的度不是偶数            {                flag = false;                break;            }        }        if(flag)  //欧拉回路存在        {            cout<<1<<endl;        }        else   //欧拉回路不存在        {            cout<<0<<endl;        }    }}

0 0
原创粉丝点击