欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结
束。
Output
每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
Sample Input
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
Sample Output
1
0
思路:1.节点的度一定是非负偶数;2.并查集判断图是否连通;
模板:https://blog.csdn.net/queque_heiya/article/details/105783259
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
const int maxa=1e3+10;
int n,m;
int cnt[maxa];
int father[maxa];
int find(int x){
if(father[x]==-1)
return x;
return father[x]=find(father[x]);
}
void unit(int x,int y){
x=find(x);
y=find(y);
if(x!=y)
father[x]=y;
}
bool check(){
int count=0;//记录连通分量的个数
for(int i=1;i<=n;i++)
if(find(i)==i)
count++;
return count>1?false:true;
}
int main(){//判断每一个节点的度数是否为偶数即可 + 图必须是连通的
while(scanf("%d",&n)!=EOF&&n){
memset(father,-1,sizeof(father));
memset(cnt,0,sizeof cnt);
scanf("%d",&m);
int e1,e2;
for(int i=0;i<m;i++){
scanf("%d%d",&e1,&e2);
cnt[e1]++;
cnt[e2]++;
unit(e1,e2);
}
int ans=0;
for(int i=1;i<=n;i++)
if(cnt[i]&&cnt[i]%2==0) ans++;
printf("%d\n",ans==n&&check()?1:0);
}
}