欧拉回路

来源:互联网 发布:遍历算法的缺点 编辑:程序博客网 时间:2024/06/05 06:30

欧拉回路

总时间限制: 
1000ms 
内存限制: 
65536kB
描述

欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路

给定一个无向图,请判断该图是否存在欧拉回路

输入
输入数据包含若干测试用例
每个测试用例的第一行是两个正整数,分别表示图的节点数N(1 < N < 1000)和边数M
随后的M行对应M条边,每行有两个正整数,分别表示这条边上的两个节点的编号(节点编号从1到N)
当N为0时输入结束
输出
每个测试用例的输出占一行,若存在欧拉回路则输出1,否则输出0
样例输入
3 31 21 32 33 21 22 30
样例输出
10
     
#include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<iomanip>#include<queue>#include<stack>#include<vector>#include<set>#include<map>using namespace std;int V[1005];int father[1005];int Getfather(int x){if(x==father[x])return x;int tmp=Getfather(father[x]);father[x]=tmp;return tmp;}int main(){int n,m,s,t;while(cin>>n&&n){memset(V,0,sizeof(V));for(int i=1;i<=n;++i){father[i]=i;}cin>>m;while(m--){cin>>s>>t;V[s]++;V[t]++;int fs=Getfather(s);int ft=Getfather(t);if(fs!=ft){father[fs]=ft;}}int f=Getfather(1);bool flag=true;for(int i=1;i<=n;++i){if(V[i]%2==1||Getfather(i)!=f){flag=false;break;}}if(flag)cout<<1<<endl;else cout<<0<<endl;}return 0;}