Problem Description
欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
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
Author
ZJU
Source
本题是给图判断图中是否存在欧拉回路,欧拉回路的含义题目中也说明了,本题的思路就是并查集判断图是否连通,如果不连通不可能存在欧拉回路,如果连通了判断欧拉回路存在的条件是图中各点的度全部为偶数(所以这里需要注意将存放顶点度的数组初始化)。
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int maxx = 1005;
int pre[maxx],cnt,du[maxx];
void init(int n){
int i;
memset(du,0,sizeof(du));
for(i=1;i<=n;++i){
pre[i] = i;
}
}
int root(int x){
if(x!=pre[x]){
pre[x] = root(pre[x]);
}
return pre[x];
}
void merge(int x,int y){
int fa = root(x);
int fb = root(y);
if(fa!=fb){
--cnt;
pre[fa] = fb;
}
}
int main(){
int n,m,x,y,i;
while(scanf("%d",&n) && n){
init(n);
cnt = n-1;
scanf("%d",&m);
for(i=0;i<m;++i){
scanf("%d %d",&x,&y);
++du[x];
++du[y];
merge(x,y);
}
if(cnt!=0){
printf("0\n");
continue;
}
bool flg = true;
for(i=0;i<n;++i){
if(du[i]%2!=0){
flg = false;
break;
}
}
if(flg){
printf("1\n");
}else{
printf("0\n");
}
}
return 0;
}