数据结构与算法题目集(中文)7-32 哥尼斯堡的“七桥问题” (25分)

1题目

哥尼斯堡是位于普累格河上的一座城市,它包含两个岛屿及连接它们的七座桥,如下图所示。

可否走过这样的七座桥,而且每桥只走过一次?瑞士数学家欧拉(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

2.题目分析

1.欧拉回路:连通图,不存在奇数顶点,要通过所有边一次且仅仅一次行遍所有顶点才叫欧拉图

欧拉回路判断:

无向图存在欧拉回路的充要条件

一个无向图存在欧拉回路,当且仅当该图所有顶点度数都为偶数,且该图是连通图。(百度百科)

2.方法

1.使用DNS扫描能够遍历所有的点+判断度数都为偶数

2.使用并查集+判断度数都为偶数

3.代码

方法一(注意:开始a,b的输入都是用的cin,但是最后两个测试点超时,改成scanf通过

#include<iostream>
#include<cstdio>
using namespace std;
#define max 1001
#define INF 100001
int edges[max][max];
int visited[max] = { 0 };
int countlist[max] = { 0 };
int n, m;
void DFS(int v)
{

	visited[v] = 1;
	for (int i = 1; i <=n; i++)
	{
		if (edges[v][i] != 0 && edges[v][i] != INF&&visited[i] == 0)
		{
			DFS(i);
		}
	}

}

int main()
{
	cin >> n >> m;
	for (int i = 0; i < max; i++)
	{
		for (int j = 0; j < max; j++)
		{
			if (i == j)edges[i][j] = 0;
			else edges[i][j] = INF;
		}
	}

	for (int i = 0; i < m; i++)
	{
		int a, b;
		scanf("%d %d", &a, &b);
		edges[a][b] = 1;
		edges[b][a] = 1;
		countlist[a]++;
		countlist[b]++;
	}
	DFS(1);
	for (int i = 1; i <=n; i++)
	{
		if (visited[i] == 0 || countlist[i] % 2 != 0) { cout << 0 << endl; return 0; }
	}
cout << 1 << endl;
return 0;	
}

方法二

//并查集+度数取余2为0
#include<iostream>
using namespace std;
int degree[2000] = {0};
int f[2000];
int find(int root)
{
	int son, temp;
	son = root;
	while (root != f[root])
		root = f[root];
	while (son != root)
	{
		temp = f[son];
		f[son] = root;
		son = temp;
	}
	return root;
}



int main()
{
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <=n; i++)
	{
		f[i] = i;
	}

	for (int i = 0; i < m; i++)
	{
		int a, b;
		cin >> a >> b;
		degree[a]++;
		degree[b]++;
		int fa = find(a);
		int fb = find(b);
		if (fa != fb)
			f[fa] = fb;
	}
	int cnt = 0;
	for (int i = 1; i <=n; i++)
	{
		if (f[i] == i)
			cnt++;
	}
	if (cnt != 1)
	{
		cout << 0;
		return 0;
	}
	for(int i=1;i<=n;i++)
	{
		if (degree[i] % 2 != 0)
		{
			cout << 0;
			return 0;
		}
	}
	cout << 1;

}
发布了47 篇原创文章 · 获赞 1 · 访问量 432

猜你喜欢

转载自blog.csdn.net/qq_42325947/article/details/104239335