hdu 1878 欧拉回路(联通<并查集> + 偶数点)

时间:2021-03-08 16:04:00
欧拉回路
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18576    Accepted Submission(s): 7219
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
 
Sample Output
1
0

C/C++:

 #include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <climits>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int my_max = ; int n, m, my_pre[my_max], a, b, my_node[my_max]; int my_find(int x)
{
int n = x;
while (n != my_pre[n])
n = my_pre[n];
int i = x, j;
while (n != my_pre[i])
{
j = my_pre[i];
my_pre[i] = n;
i = j;
}
return n;
} bool is_eulerian()
{
for (int i = ; i <= n; ++ i)
if (my_node[i] & ) return false;
int temp = my_find();
for (int i = ; i <= n; ++ i)
if (my_find(i) != temp) return false;
return true;
} int main()
{
while (scanf("%d", &n), n)
{
scanf("%d", &m);
memset(my_node, , sizeof(my_node));
for (int i = ; i <= n; ++ i)
my_pre[i] = i; while (m --)
{
scanf("%d%d", &a, &b);
my_node[a] ++, my_node[b] ++;
int n1 = my_find(a), n2 = my_find(b);
my_pre[n1] = n2;
} if (is_eulerian()) printf("1\n");
else printf("0\n");
}
return ;
}