http://ac.jobdu.com/problem.php?pid=1027

題目描述:
    歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條迴路。現給定一個圖,問是否存在歐拉回路?
輸入:
    測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是節點數N ( 1 < N < 1000 )和邊數M;隨後的M行對應M條邊,每行給出一對正整數,分別是該條邊直接連通的兩個節點的編號(節點從1到N編號)。當N爲0時輸入結束。
輸出:
    每個測試用例的輸出佔一行,若歐拉回路存在則輸出1,否則輸出0。
樣例輸入:
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
樣例輸出:
1
0

  1. #include<iostream>  
  2. #include<cstdio>  
  3. #include<cmath>  
  4. #include<algorithm>  
  5. #include<cstdlib>  
  6. #include<memory.h>  
  7. #include<cstring>  
  8.   
  9. using namespace std;  
  10. int father[1001];  
  11. int degree[1001];  
  12. int getfather(int i){  
  13.     if(father[i]==i)  
  14.         return i;  
  15.     return father[i] = getfather(father[i]);  
  16. }  
  17. void merge(int i, int j){  
  18.     int fa = getfather(i);  
  19.     int fb = getfather(j);  
  20.     if(fa!=fb)  
  21.         father[fa] = fb;  
  22. }  
  23. int main(){  
  24.   
  25.    //freopen("in.txt", "r", stdin);  
  26.      
  27.     int n, m;  
  28.     int a, b;  
  29.     while(cin>>n>>m){  
  30.         memset(degree, 0, sizeof(degree));  
  31.   
  32.         for(int i=1;i<=n;++i)  
  33.             father[i] = i;  
  34.   
  35.         for(int i=0;i<m;++i){  
  36.             scanf("%d%d", &a, &b);  
  37.             degree[a]++;  
  38.             degree[b]++;  
  39.             merge(a, b);  
  40.               
  41.         }  
  42.         int f = getfather(1);  
  43.         bool flag = true;  
  44.         for(int i=1;i<=n;++i){  
  45.             if(getfather(i)!=f || degree[i]==0 || degree[i]&1){  
  46.                 flag = false;  
  47.                 break;  
  48.             }  
  49.         }  
  50.         if(flag)  
  51.             printf("1\n");  
  52.         else  
  53.             printf("0\n");  
  54.     }  
  55.     //fclose(stdin);  
  56. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章