(歐拉回路 並查集 別犯傻逼的錯了) 7:歐拉回路 OpenJudge 數據結構與算法MOOC / 第七章 圖 練習題(Excercise for chapter7 graphs)

描述

歐拉回路是指不令筆離開紙面,可畫過圖中每條邊僅一次,且能夠回到起點的一條迴路ios

給定一個無向圖,請判斷該圖是否存在歐拉回路測試

輸入
輸入數據包含若干測試用例
每一個測試用例的第一行是兩個正整數,分別表示圖的節點數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

 

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;
}
相關文章
相關標籤/搜索