問題鏈接:HDU1878 歐拉回路。
問題簡述:輸入若干測試用例,判定一個無向圖是否有歐拉回路。
問題分析:無向圖的歐拉回路需要滿足兩個條件,一是圖是連通的,二是各個結(jié)點的入出度相同(有偶數(shù)個連接的邊)。
程序說明:程序中用并查集判定圖是否連通,對圖構(gòu)造一個并查集(樹)后,如果連通則其根相同。用數(shù)組degree[]統(tǒng)計各個結(jié)點的連通度。
AC的C++語言程序如下:
/* HDU1878 歐拉回路 */#include <iostream>#include <cstring>#include <vector>using namespace std;// 并查集類class UF {PRivate: vector<int> v;public: UF(int n) { for(int i=0; i<=n; i++) v.push_back(i); } int Find(int x) { for(;;) { if(v[x] != x) x = v[x]; else return x; } } bool Union(int x, int y) { x = Find(x); y = Find(y); if(x == y) return false; else { v[x] = y; return true; } }};const int MAXN = 1000;int degree[MAXN+1];int main(){ int n, m, src, dest; while(cin >> n && n != 0) { UF uf(n); cin >> m; // 變量初始化 memset(degree, 0, sizeof(degree)); // 統(tǒng)計各個結(jié)點的聯(lián)通度,并構(gòu)建并查集(為判定圖是否為連通圖) while(m--) { cin >> src >> dest; degree[src]++; degree[dest]++; if(uf.Find(src) != uf.Find(dest)) uf.Union(src, dest); } // 判定 int root = uf.Find(1), ans = 1; for(int i=1; i<=n; i++) if(uf.Find(i) != root || degree[i] & 1 /*degree[i] % 2 == 1*/) { ans = 0; break; } // 輸出結(jié)果 cout << ans << endl; } return 0;}
新聞熱點
疑難解答