PTA哥尼斯堡的“七桥问题”(欧拉回路+并查集)

哥尼斯堡是位于普累格河上的一座城市,它包含两个岛屿及连接它们的七座桥,
可否走过这样的七座桥,而且每桥只走过一次?瑞士数学家欧拉(Leonhard Euler,1707—1783)最终解决了这个问题,并由此创立了拓扑学。
这个问题如今可以描述为判断欧拉回路是否存在的问题。欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个无向图,问是否存在欧拉回路?

输入格式:

输入第一行给出两个正整数,分别是节点数N (1≤N≤1000)和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。

输出格式:

若欧拉回路存在则输出1,否则输出0。

输入样例1:

6 10
1 2
2 3
3 1
4 5
5 6
6 4
1 4
1 6
3 4
3 6

输出样例1:

1

输入样例2:

5 8
1 2
1 3
2 3
2 4
2 5
5 3
5 4
3 4

输出样例2:

0


思路:
如果欧拉通路的起点与终点一样,则成为欧拉回路, 连通的多重图具有欧拉回路当且仅当它的每个顶点都有偶数度 则欧拉回路的条件:
  • 图是连通的,没有孤立节点
  • 无向图的每个节点的度数都是偶数度,有向图每个节点的入度等于出度

使用并查集统计连通分量个数,使用degree数组奇偶数判断是否全为偶数。

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
int fa[1005];
int father(int x){
	if(fa[x]==x) return x;
	return fa[x] = father(fa[x]);
} 
int main(){
	int n,m,x,y;
	cin >> n >> m;
	int degree[n+1];
	for(int i=1;i<=n;i++)  fa[i] = i;
	memset(degree,0,sizeof(degree));
	for(int i=0;i<m;i++){
		cin >> x >> y;
		int rootx = father(x),rooty = father(y);
		if(rootx!=rooty){
			fa[rooty] = rootx;
		}
		// fa[father(y)] = father(x);  这样写竟然会超时!!!!
		// 不要问我咋知道的
		degree[x]++;
		degree[y]++;
	}
	int exist=1,root = fa[1],connectcnt = 0;
	for(int i=1;i<=n;i++){
		if(fa[i]==i) connectcnt++;
	}
	if(connectcnt>1) exist = 0;
	for(int i=1;i<=n;i++){
		if(degree[i]%2){
			exist = 0;break;
		}
	} 
	cout << exist << endl;	
	return 0;
}

发布了63 篇原创文章 · 获赞 34 · 访问量 6549

猜你喜欢

转载自blog.csdn.net/SinclairWang/article/details/104045924