hdu1878 歐拉迴路(並查集)

來源:互聯網
上載者:User

標籤:並查集   hdu   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1878

Problem Description歐拉迴路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條迴路。現給定一個圖,問是否存在歐拉迴路? Input測試輸入包含若干測試案例。每個測試案例的第1行給出兩個正整數,分別是節點數N ( 1 < N < 1000 )和邊數M;隨後的M行對應M條邊,每行給出一對正整數,分別是該條邊直接連通的兩個節點的編號(節點從1到N編號)。當N為0時輸入結
束。 Output每個測試案例的輸出佔一行,若歐拉迴路存在則輸出1,否則輸出0。
 Sample Input
3 31 21 32 33 21 22 30
 Sample Output
10

無向歐拉圖的歐拉迴路存在的充要條件:連通且沒有奇點;
歐拉路徑存在的充要條件:連通且奇點個數為2;
有向歐拉圖的歐拉迴路存在的充要條件:基圖連通且所有頂點的入度等於出度;
歐拉路徑存在的充要條件:基圖連通且存在某頂點入度比出度多一,
另一頂點出度比入度多一,其餘頂點入度等於出度。


代碼如下:

#include <cstdio>#include <cstring>int father[1017];int n, m;int find(int x){return x==father[x]?x:father[x]=find(father[x]);}void init(){for(int i = 0; i <= n; i++){father[i] = i;}}void Union(int x, int y){int f1 = find(x);int f2 = find(y);if(f1 != f2)father[f2] = f1;}int main(){int i, j;int a, b;int cal[1017];while(scanf("%d",&n)&& n){init();memset(cal,0,sizeof(cal));if(n == 0)break;scanf("%d",&m);for(i = 0; i < m; i++){scanf("%d%d",&a,&b);Union(a,b);cal[a]++,cal[b]++;}int flag = 0;int t = father[1];for(i = 1; i <= n; i++){if(cal[i]%2 == 1 || father[i] != t){flag = 1;break;}}if(flag)printf("0\n");elseprintf("1\n");}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.