欧拉回路

欧拉回路

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 4   Accepted Submission(s) : 1
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:联通;2:节点为偶数
 1 #include<stdio.h>
 2 #include<string.h>
 3 int road[1010],num[1010];
 4 int find(int x){
 5     int r=x;
 6     while(r!=road[r])r=road[r];
 7     int i=x,j;
 8     while(i!=r)j=road[i],road[i]=r,i=j;
 9     return r;
10 }
11 int main(){
12     int N,M,node1,node2,f1,f2,flot,first;
13     while(scanf("%d",&N),N){
14     memset(road,0,sizeof(road)); 
15     memset(num,0,sizeof(num));
16         scanf("%d",&M);
17         for(int i=1;i<=N;++i)road[i]=i;
18         flot=0;
19         while(M--){
20             scanf("%d%d",&node1,&node2);
21             f1=find(node1);f2=find(node2);
22             if(f1!=f2)road[f2]=f1;
23             else flot=1;
24             num[node1]++;num[node2]++;
25         }int exist=0;
26         for(int i=1;i<=N;++i){
27         if(road[i]==i)exist++;
28         if(exist>1)break;
29         if(num[i]&1){
30             flot=0;break;
31         }
32         }
33         if(exist==1&&flot)flot=1;
34         else flot=0;
35         if(flot==1)puts("1");
36         else puts("0");
37     }
38     return 0;
39 }
原文地址:https://www.cnblogs.com/handsomecui/p/4629081.html