题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1878
思路分析:该问题给定一个无向图,要求判断该无向图是否存在欧拉回路;无向图判断存在欧拉回路的两个必要条件:该无向图为连通图且所有的结点的度数为偶数;
代码如下:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int MAX_N = 1000 + 10; int fa[MAX_N]; int link[MAX_N]; void Init() { for (int i = 0; i < MAX_N; ++i) { fa[i] = i; link[i] = 0; } } int Find(int a) { if (fa[a] == a) return a; else return fa[a] = Find(fa[a]); } int Union(int a, int b) { int fa_a = Find(a); int fa_b = Find(b); if (fa_a == fa_b) return -1; if (fa_a > fa_b) fa[fa_b] = fa_a; else fa[fa_a] = fa_b; return 1; } int main() { int ver_num, road_num; int ver_1, ver_2; while (scanf("%d", &ver_num) != EOF && ver_num) { scanf("%d", &road_num); Init(); for (int i = 0; i < road_num; ++i) { scanf("%d %d", &ver_1, &ver_2); link[ver_1]++; link[ver_2]++; Union(ver_1, ver_2); } int set_count = 0; bool ok = true; for (int i = 1; i <= ver_num; ++i) { if (fa[i] == i) set_count++; if ((link[i] & 1) != 0 || set_count > 1) ok = false; if (!ok) break; } if (ok) printf("1\n"); else printf("0\n"); } return 0; }
时间: 2024-10-11 05:53:20