- 題目描述:
-
歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且可以回到起點的一條迴路。現給定一個圖,問是否存在歐拉回路?
- 輸入:
-
測試輸入包含若干測試用例。每個測試用例的第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
- #include<iostream>
- #include<cstdio>
- #include<cmath>
- #include<algorithm>
- #include<cstdlib>
- #include<memory.h>
- #include<cstring>
- using namespace std;
- int father[1001];
- int degree[1001];
- int getfather(int i){
- if(father[i]==i)
- return i;
- return father[i] = getfather(father[i]);
- }
- void merge(int i, int j){
- int fa = getfather(i);
- int fb = getfather(j);
- if(fa!=fb)
- father[fa] = fb;
- }
- int main(){
- //freopen("in.txt", "r", stdin);
- int n, m;
- int a, b;
- while(cin>>n>>m){
- memset(degree, 0, sizeof(degree));
- for(int i=1;i<=n;++i)
- father[i] = i;
- for(int i=0;i<m;++i){
- scanf("%d%d", &a, &b);
- degree[a]++;
- degree[b]++;
- merge(a, b);
- }
- int f = getfather(1);
- bool flag = true;
- for(int i=1;i<=n;++i){
- if(getfather(i)!=f || degree[i]==0 || degree[i]&1){
- flag = false;
- break;
- }
- }
- if(flag)
- printf("1\n");
- else
- printf("0\n");
- }
- //fclose(stdin);
- }