Dijkstra函数模板(c++)

        auto dj = [&](int start, vector<long long>& dis, vector<vector<pair<int,int>>>& mp){
            priority_queue<pair<long long,int>> q;
            dis[start] = 0;
            q.push({0, start});
            while(!q.empty()){
                auto [cost, cur] = q.top();
                q.pop();
                if(cost>dis[cur])  continue;
                for(auto [next, distance]: mp[cur]){
                    if(dis[next]<=cost+distance) continue;
                    dis[next] = cost+distance;
                    q.push({dis[next], next});
                }
            }
        };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Dijkstra算法的C++模板实现: ```c++ #include <iostream> #include <vector> #include <queue> #include <limits.h> using namespace std; template<typename T> class Dijkstra { public: Dijkstra(int n) : adj(n), dist(n, numeric_limits<T>::max()), visited(n, false) {} void addEdge(int u, int v, T w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } void shortestPath(int start) { priority_queue<pair<int, T>, vector<pair<int, T>>, greater<pair<int, T>>> pq; pq.push(make_pair(start, 0)); dist[start] = 0; while (!pq.empty()) { int u = pq.top().first; pq.pop(); if (visited[u]) continue; visited[u] = true; for (auto& p : adj[u]) { int v = p.first; T w = p.second; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; pq.push(make_pair(v, dist[v])); } } } } T getDistance(int u) { return dist[u]; } private: vector<vector<pair<int, T>>> adj; vector<T> dist; vector<bool> visited; }; int main() { int n = 5; Dijkstra<int> dijkstra(n); dijkstra.addEdge(0, 1, 2); dijkstra.addEdge(0, 3, 1); dijkstra.addEdge(1, 2, 3); dijkstra.addEdge(1, 3, 2); dijkstra.addEdge(2, 4, 1); dijkstra.addEdge(3, 4, 4); dijkstra.shortestPath(0); for (int i = 0; i < n; i++) cout << "Distance from 0 to " << i << ": " << dijkstra.getDistance(i) << endl; return 0; } ``` 该类模板实现了Dijkstra算法,使用了邻接表来表示图,`addEdge`函数用于添加边,`shortestPath`函数用于计算从起点到其他点的最短距离,`getDistance`函数用于获取某个点到起点的最短距离。在main函数中,我们通过创建一个Dijkstra对象,添加边并调用`shortestPath`函数来计算最短路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值