1126. Eulerian Path (25)[欧拉回路]

本文介绍了一种基于邻接表实现的算法,用于判断给定图是否为欧拉回路或半欧拉回路,并提供了一个已通过PAT-A 1126测试的C++代码示例。

1. 原题:https://www.patest.cn/contests/pat-a-practise/1126

2. 思路:

题意:给出一个图,判断是否欧拉回路。
思路:
其实这题不懂欧拉回路的也没关系,题目已经给出了判断条件。
即:
1.连通图且所有结点的度都是偶数,是欧拉回路。
2.连通图且只有两个点的度是奇数,是半欧拉。
3.剩下的都不是欧拉回路。
根据条件,思路也就有了。
图可以用邻接矩阵或者邻接表表示。
这里用邻接表表示方便些。因为邻接表中的头结点的容量就是度。


首先用dfs判断是否连通。
然后判断度就可以了
已AC。

3. 源码:

#include <iostream>
#include <vector>
using namespace std;

vector< vector<int> > G;//图的邻接表表示法
int N;//总结点数
int visited[500+5] = { 0 };//判断是否访问过下标表示的结点
int cnt = 0;//统计连通图中的结点数

void dfs(int start);//递归遍历连通图

int main()
{
	//freopen("in.txt", "r", stdin);
	int M;
	cin >> N >> M;
	G.resize(N + 1);
	for (int i = 0; i < M; i++)//读入数据
	{
		int a, b;
		cin >> a >> b;
		G[a].push_back(b);
		G[b].push_back(a);
	}

	int oddCnt = 0;//奇数度的结点数目
	for (int i = 1; i <= N; i++)
	{
		if (i != 1)
			cout << ' ';
		cout << G[i].size();

		if (G[i].size() % 2 != 0)
			oddCnt++;
	}
	
	dfs(1);
	if (cnt == N)//表示连通
	{
		if (oddCnt == 0)
			cout << "\nEulerian" << endl;
		else if (oddCnt == 2)
			cout << "\nSemi-Eulerian" << endl;
		else
			cout << "\nNon-Eulerian" << endl;
	}
	else
		cout << "\nNon-Eulerian" << endl;

	return 0;
}

void dfs(int start)//递归遍历连通图
{
	visited[start] = 1;
	cnt++;
	for (int i = 0; i < G[start].size(); i++)
	{
		if (visited[G[start][i]] == 0)
			dfs(G[start][i]);
	}

	return;
}


很抱歉,作为一个文本AI助手,我无法提供视频资源。但是我可以为您提供欧拉回路算法的编程示例。以下是一个使用Python实现的欧拉回路算法的示例代码: ```python from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) def dfs(self, v, visited): visited[v] = True for i in self.graph[v]: if visited[i] == False: self.dfs(i, visited) def is_connected(self): visited = [False] * (max(self.graph) + 1) for i in self.graph: if len(self.graph[i]) > 0: self.dfs(i, visited) break for i in self.graph: if visited[i] == False and len(self.graph[i]) > 0: return False return True def is_eulerian(self): if self.is_connected() == False: return False odd_degree_count = 0 for i in self.graph: if len(self.graph[i]) % 2 != 0: odd_degree_count += 1 if odd_degree_count == 0: return True elif odd_degree_count == 2: return True else: return False def eulerian_path(self): if self.is_eulerian() == False: return "No Eulerian path exists." else: return "Eulerian path exists." # 创建一个图对象 g = Graph() # 添加边 g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 3) g.add_edge(2, 4) g.add_edge(3, 4) # 判断是否存在欧拉回路 print(g.eulerian_path()) ``` 这段代码使用了邻接表来表示图的存储结构,并使用深度优先搜索算法来判断图是否连通。然后,根据图的度数来判断是否存在欧拉回路。最后,根据判断结果输出相应的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值