[最短路]uva 12295 Optimal Symmetric Paths

这篇博客探讨了UVA 12295问题的解决方法,通过动态规划(DP)策略寻找图中起点到终点的最优对称路径。文章详细阐述了如何利用pair数据结构扩展C语言实现这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**

uva 12295 Optimal Symmetric Paths__DP 

正解,最短路 */ #include <stdio.h> #include <string.h> #include <vector> #include <queue> #include <algorithm> using namespace std; #define N 1005 #define INF 1000000000LL #define MOD 1000000009LL struct node { int d,x,y; node(int a = 0,int b = 0,int c = 0) { x = a; y = b; d = c; } }; bool operator<(node a,node b) { return a.d > b.d; } #define MK node __int64 d[N][N],ds[N][N]; int n,mat[N][N]; bool vis[N][N]; node p,pt; int move[][2]= {0,1,1,0,0,-1,-1,0}; i
### 使用迪杰斯特拉算法求解图中任意两点之间的短路径 #### 初始化阶段 为了计算从起点 `s` 到终点 `t` 的短路径,初始化工作非常重要。对于每一个节点 `v`,设置其距离为无穷大(除了起始节点外),并创建一个优先队列来存储待处理的节点及其当前估计的距离。 ```python import heapq def initialize_single_source(graph, start_vertex): distances = {vertex: float('infinity') for vertex in graph} previous_vertices = {vertex: None for vertex in graph} distances[start_vertex] = 0 priority_queue = [(0, start_vertex)] return distances, previous_vertices, priority_queue ``` #### 主循环逻辑 通过不断提取具有小临时距离标记的未处理节点来进行迭代更新操作直到遍历完所有可达节点为止。每次从未处理过的节点集中选取拥有低成本到达记录的一个作为新的“已知区域”,并对该节点直接相连的所有邻居重新评估可能更优的新路径长度[^2]。 ```python def dijkstra_algorithm(graph, start_vertex, end_vertex=None): distances, previous_vertices, pq = initialize_single_source(graph, start_vertex) while pq: current_distance, current_vertex = heapq.heappop(pq) if current_vertex == end_vertex: break for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance previous_vertices[neighbor] = current_vertex heapq.heappush(pq, (distance, neighbor)) return distances[end_vertex], reconstruct_path(previous_vertices, start_vertex, end_vertex) def reconstruct_path(predecessors, start_vertex, target_vertex): path = [] step = target_vertex while step is not None: path.append(step) step = predecessors.get(step) return list(reversed(path)) if path[-1] == start_vertex else "No valid path" ``` #### 处理无向加权图的数据结构定义 这里采用邻接表的形式表示输入图形数据,其中键代表各个顶点而对应的值则是一个字典用来保存相邻结点以及它们间连接边上的权重信息[^3]。 ```python graph_representation = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } start_point = 'A' end_point = 'D' shortest_distance, optimal_route = dijkstra_algorithm(graph_representation, start_point, end_point) print(f"The shortest distance from node '{start_point}' to node '{end_point}' is {shortest_distance}.") print(f"One of the possible paths with this minimum cost is: {' -> '.join(optimal_route)}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值