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
欧拉回路: 无向图连通图的判断条件 --->> 所有点的度为偶数
有向图连通图的判断条件 --->> 出度+1,入度-1,所有点的度为0
欧拉路径: 无向图连通图的判断条件 --->> ① 所有点的度为偶数
② 其余点为偶数,有且仅有两个奇数度的点(一个为起点,一个为终点)
有向图连通图的判断条件 --->> ①出度+1,入度-1,所有点的度为0
②有且仅有两个点的度不为0,一个为1,一个为 -1
上述条件均需一个大条件,图为连通图!
所以此题用并查集判断是否连通
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
int d[maxn];
using namespace std;
int par[maxn];
int num[maxn];
void init()
{
for(int i=0;i<maxn;i++)
par[i]=i,num[i]=1;
}
int find(int x)
{
if(par[x]!=x)
par[x]=find(par[x]);
return par[x];
}
void Union(int x,int y)
{
int xx=find(x);
int yy=find(y);
if(xx!=yy){
par[xx]=yy;
num[yy]+=num[xx];
}
}
int main(){
int n,m;
ios::sync_with_stdio(false);
while(1){
cin>>n;
if(n==0) return 0;
cin>>m;
init();
memset(d,0,sizeof(d));
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
Union(a,b);
d[a]++;
d[b]++;
}
bool f=1,g=0;
for(int i=1;i<=n;i++){
if( d[i]%2==1) f=0; //存在奇数点
if( num[i]==n ) g=1; //表示连通
}
if( f && g ) cout<<"1"<<endl;
else cout<<"0"<<endl;
}
return 0;
}