欧拉回路
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16538 Accepted Submission(s): 6397
Problem Description
欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结
束。
Output
每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
Sample Input
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
1 2
1 3
2 3
3 2
1 2
2 3
0
Sample Output
10
Author
ZJU
Source
问题链接:HDU1878 欧拉回路。
问题简述:
输入若干测试用例,判定一个无向图是否有欧拉回路。
问题分析:
无向图的欧拉回路需要满足两个条件,一是图是连通的,二是各个结点的入出度相同(有偶数个连接的边)。
程序说明:
程序中用并查集判定图是否连通,对图构造一个并查集(树)后,如果连通则其根相同。用数组degree[]统计各个结点的连通度。
程序不够简洁,又写了一个简洁版。
AC的C++语言程序(简洁版)如下:
/* HDU1878 欧拉回路 */
#include <iostream>
#include <string.h>
using namespace std;
const int N = 1000;
int f[N + 1], cnt;
void UFInit(int n)
{
for(int i = 1; i <=n; i++)
f[i] = i;
cnt = n;
}
int Find(int a) {
return a == f[a] ? a : f[a] = Find(f[a]);
}
void Union(int a, int b)
{
a = Find(a);
b = Find(b);
if (a != b) {
f[a] = b;
cnt--;
}
}
const int N2 = 1000;
int degreeout[N2+1];
int main()
{
int n, m, src, dest;
while(cin >> n && n != 0) {
// 初始化并查集
UFInit(n);
// 变量初始化
memset(degreeout, 0, sizeof(degreeout));
// 统计各个结点的联通度,并构建并查集(为判定图是否为连通图)
cin >> m;
while(m--) {
cin >> src >> dest;
degreeout[src]++;
degreeout[dest]++;
Union(src, dest);
}
// 判定
int ans = 1;
if(cnt != 1)
ans = 0;
else
for(int i=1; i<=n; i++)
if(degreeout[i] & 1 /*degree[i] % 2 == 1*/) {
ans = 0;
break;
}
// 输出结果
cout << ans << endl;
}
return 0;
}
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));
// 统计各个结点的联通度,并构建并查集(为判定图是否为连通图)
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;
}
// 输出结果
cout << ans << endl;
}
return 0;
}