dijkstra模板矩阵存法

#include<iostream>
#include<string>
#include<map>
using namespace std;
const int maxx=1010;
const int inf=0x3f3f3f3f;
int g[maxx][maxx],d[maxx],n,k;
bool vis[maxx];
void dijkstra(int x){
 fill(d,d+maxx,inf);
 fill(vis,vis+maxx,false);
 d[x]=0;
 for(int i=1;i<=n;i++){
  int u=-1,minn=inf;
  for(int j=1;j<=n;j++){
   if(d[j]<minn&&vis[j]==false){
    u=j;
    minn=d[j];
   }
  }
  if(u==-1) break;
  vis[u]=true;
  for(int j=1;j<=n;j++){
   if(vis[j]==false&&g[u][j]!=inf&&d[j]>d[u]+g[u][j])
   d[j]=d[u]+g[u][j];
  }
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dijkstra算法是一种用于寻找图中两点之间最短路径的经典算法。在C++14中,你可以使用模板来编写一个通用的Dijkstra实现,适用于不同类型的数据结构(如邻接矩阵或邻接表)。下面是一个简化的模板版本,假设我们使用`std::pair<int, int>`来表示节点之间的权重和距离: ```cpp #include <iostream> #include <vector> #include <queue> #include <utility> template <typename T, typename Weight = std::pair<int, int>> struct Graph { // ...定义节点和边的结构... }; template <typename Graph, typename Distance = typename Graph::Weight> class Dijkstra { public: void dijkstra(const Node& start) { priority_queue<std::pair<Distance, Node>, std::vector<std::pair<Distance, Node>>, std::greater<Distance>> pq; visited[start.index] = true; pq.push(std::make_pair(start.distance, start)); while (!pq.empty()) { auto current = pq.top(); pq.pop(); if (visited[current.second.index]) continue; // 更新邻居的最短距离 for (const auto& neighbor : current.second.neighbors) { const Distance new_distance = current.first + neighbor.weight; if (!visited[neighbor.index] || new_distance < distances[neighbor.index]) { distances[neighbor.index] = new_distance; pq.push(std::make_pair(new_distance, neighbor)); } } } } private: std::vector<bool> visited; std::vector<Distance> distances; // 存储每个节点的已知最短距离 }; // 使用示例: int main() { Graph<int> graph; // 假设这是你的图实例 Dijkstra(Graph<int>, std::make_pair<int, int>> dijkstra(graph); dijkstra.dijkstra(graph.get_start_node()); return 0; } ``` 在这个例子中,`T`代表图中的节点类型,而`Weight`则是节点之间的权重类型。注意,这只是一个基础模板,并未包含所有细节,如处理无权图或负权重的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值