歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且能夠回到起點的一條迴路ios
給定一個無向圖,請判斷該圖是否存在歐拉回路測試
3 3 1 2 1 3 2 3 3 2 1 2 2 3 0
1 0
emmmmm,犯了一個很傻逼的錯了spa
最後,這個判斷一個圖是否有歐拉回路的條件:1)圖是連通的。 2)每一個結點的度之和必須爲偶數。code
只有同時知足這兩個條件,才能判斷歐拉回路存在。blog
C++代碼:ci
#include<iostream> #include<stdio.h> using namespace std; const int maxn = 1010; int n,m; int father[maxn]; int node[maxn]; int Find(int a){ while(a != father[a]){ father[a] = father[father[a]]; a = father[a]; } return a; } void Union(int a,int b){ int ax = Find(a); int bx = Find(b); if(ax != bx) father[ax] = bx; } int main(){ while(cin>>n){ if(n == 0) break; cin>>m; for(int i = 1; i <= n; i++){ father[i] = i; node[i] = 0; } int x,y; for(int i = 1;i <= m; i++){ cin>>x>>y; node[x]++; node[y]++; Union(x,y); } int cnt = 0; int flag = 1; int cnt1 = 0; for(int i = 1; i <= n; i++){ //要認真啊啊啊,i <= n 不是 i <= m..... if(father[i] == i){ cnt++; if(cnt == 2) flag = 0; } if(node[i] & 1) cnt1++; } if(cnt1 != 0) flag = 0; if(flag) cout<<1<<endl; else cout<<0<<endl; } return 0; }