Dijkstra 算法

本文介绍了一种使用优先队列实现图中从节点1到节点N的最短路径算法。通过C++代码示例详细展示了如何初始化图结构、读取边信息,并利用优先队列来更新每个节点的距离值,最终输出从起始节点到目标节点的最短路径长度。

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

使用priority_queue实现




#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <climits>
#include <ctype.h>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <deque>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>

#define mst(a,b) memset(a,b,sizeof(a));

using namespace std;

typedef long long ll;
typedef pair<int,int> P;
const int MAX_E = 100001;
const ll mod = 1000000007;
const int INF = 0x7fffffff;

struct edge{
    int to, cost;
};

const int MAX_V = 5001;

vector<edge> G[MAX_V];
int dist[MAX_V];
int N, R;

void read(){
    int a, b, c;
    cin >> N >> R;
    for(int i = 0; i < R; i++){
        cin >> a >> b >> c;
        edge e;
        e.to = b; e.cost = c;
        edge e2;
        e2.to = a; e2.cost = c;
        G[a].push_back(e);
        G[b].push_back(e2);

    }
}
// p.first = current distance
// p.second = index

void solve(){
    priority_queue < P, vector<P>, greater<P> > que;
    fill(dist, dist+N+1, INF);
    dist[1] = 0;                // from node 1
    que.push(P(0,1));

    while(!que.empty()){
        P p = que.top();
        que.pop();
        int v = p.second;
        if(dist[v] < p.first)
            continue;
        for(int j = 0; j < G[v].size(); j++){
            edge e = G[v][j];
            if(dist[e.to] > dist[v] + e.cost){
                dist[e.to] = dist[v] + e.cost;
                que.push(P(dist[e.to], e.to));
            }
        }
    }
    // from node 1 - N
    printf("the shortest path is : %d\n", dist[N]);

}

int main()
{
    read();
    solve();	
    return 0;
}


### Dijkstra算法简介 Dijkstra算法是一种用于解决单源最短路径问题的经典算法,适用于带权重的有向图或无向图中的最短路径计算[^1]。该算法的核心思想是从起始节点出发,逐步扩展已知距离最小的未访问节点,并更新其邻居节点的距离。 --- ### Dijkstra算法实现 以下是基于优先队列优化版本的Dijkstra算法实现: #### Python代码示例 ```python import heapq def dijkstra(graph, start): # 初始化距离字典,默认值为无穷大 distances = {node: float('inf') for node in graph} distances[start] = 0 # 使用堆来存储待处理节点及其当前距离 priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) # 如果当前距离大于记录的距离,则跳过此节点 if current_distance > distances[current_node]: continue # 遍历相邻节点并更新距离 for neighbor, weight in graph[current_node].items(): distance = current_distance + weight # 更新更短的距离 if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances ``` 上述代码中,`graph` 是一个邻接表形式表示的加权图,其中键是节点名称,值是一个字典,描述与其相连的其他节点以及边的权重[^2]。 --- ### Dijkstra算法的应用场景 1. **网络路由协议** 在计算机网络中,路由器可以利用Dijkstra算法找到到达目标地址的最佳路径,从而提高数据传输效率[^3]。 2. **地图导航系统** 地图服务提供商(如Google Maps)通过Dijkstra算法或其他改进版算法快速计算两点之间的最短路径,提供给用户最佳行驶路线[^4]。 3. **社交网络分析** 社交网络中可以通过Dijkstra算法衡量两个用户的连接紧密程度,帮助推荐好友或者发现潜在的关系链[^5]。 4. **物流配送规划** 物流公司使用类似的最短路径算法优化货物运输线路,减少成本和时间消耗[^6]。 --- ### 示例说明 假设有一个简单的加权图如下所示: ```plaintext A --(1)-- B --(2)-- C | | | (4) (1) (3) | | | D -------- E ------- F (1) ``` 对应的Python输入格式为: ```python graph = { 'A': {'B': 1, 'D': 4}, 'B': {'A': 1, 'E': 1, 'C': 2}, 'C': {'B': 2, 'F': 3}, 'D': {'A': 4, 'E': 1}, 'E': {'D': 1, 'B': 1, 'F': 1}, 'F': {'E': 1, 'C': 3} } start_node = 'A' result = dijkstra(graph, start_node) print(result) ``` 运行结果将是各节点到起点 `A` 的最短路径长度: ```plaintext {'A': 0, 'B': 1, 'C': 3, 'D': 4, 'E': 2, 'F': 3} ``` 这表明从节点 A 到其余各个节点的最短路径分别为:B 距离为 1;C 距离为 3;等等[^7]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值