欧拉回路
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16763 Accepted Submission(s):
6476
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
Recommend
互相连通+每个点的度都为偶数
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <algorithm> 5 #include <cmath> 6 using namespace std; 7 int a[1005]; 8 int pra[1005]; 9 int find(int x) 10 { 11 if(pra[x]==x) return x; 12 else return pra[x]=find(pra[x]); 13 } 14 void unite(int x,int y) 15 { 16 int xx=find(x); 17 int yy=find(y); 18 if(xx==yy) return; 19 else pra[x]=y; 20 } 21 int main() 22 { 23 int n,m; 24 while(cin>>n&&n) 25 { 26 cin>>m; 27 memset(a,0,sizeof(a)); 28 for(int i=1;i<=n;i++) 29 pra[i]=i; 30 for(int i=1;i<=m;i++) 31 { 32 int x,y; 33 cin>>x>>y; 34 a[x]++; 35 a[y]++; 36 unite(x,y); 37 } 38 int i; 39 int f=find(1); 40 for(i=1;i<=n;i++) 41 { 42 if(a[i]%2!=0||pra[i]!=f) 43 break; 44 } 45 if(i!=n+1) cout<<0<<endl; 46 else cout<<1<<endl; 47 } 48 return 0; 49 }