畅通工程续 (dijkstra) hdu 1874 c++

畅通工程续

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 28714    Accepted Submission(s): 10433


Problem Description
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
 

Input
本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0<N<200
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dijkstra算法是一种用于寻找图中两点之间最短路径的贪心算法。在C++中,我们可以使用优先队列(如`std::priority_queue`)来实现。以下是一个简单的Dijkstra算法的C++代码示例: ```cpp #include <iostream> #include <vector> #include <queue> #include <limits.h> struct Edge { int to, weight; }; struct Node { int id, dist = INT_MAX; // 初始距离设为无穷大 bool visited = false; bool operator<(const Node& other) const { return dist < other.dist; } }; void dijkstra(std::vector<Edge>& edges, std::vector<int>& graph, int start) { int numVertices = graph.size(); std::priority_queue<Node> pq; pq.push({start, 0}); // 将起始节点加入队列,距离为0 while (!pq.empty()) { Node current = pq.top(); // 取出距离最小的节点 pq.pop(); if (current.visited) continue; // 如果已访问过,跳过 current.visited = true; for (Edge edge : edges[current.id]) { int newDist = current.dist + edge.weight; if (newDist < graph[edge.to]) { graph[edge.to] = newDist; pq.push({edge.to, newDist}); } } } } int main() { std::vector<Edge> edges = {{0, 1}, {1, 2}, {0, 7}, {1, 6}, {2, 5}, {3, 1}, {3, 8}, {4, 3}}; std::vector<int> graph(edges.size(), INT_MAX); // 初始化图中的所有边为无穷大 dijkstra(edges, graph, 0); // 从节点0开始搜索 for (int i = 0; i < graph.size(); ++i) { if (graph[i] == INT_MAX) { std::cout << "No path found to node " << i << std::endl; } else { std::cout << "Shortest distance from node 0 to node " << i << " is: " << graph[i] << std::endl; } } return 0; } ``` 在这个代码中,`edges`是一个边的集合,`graph`是一个表示图的邻接矩阵或邻接列表,`start`是起点。算法首先将起始节点加入优先队列,然后不断取出队列中距离最小的节点,更新与其相连的边的终点的最短距离,并重新调整优先级队列。直到队列为空,遍历结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值