# Kruskal 最小生成树 & Dijkstra 最短路径

Dijkstra 算法是常见的求解单源最短路问题的算法，我们将在后面详细讲述 Dijkstra 算法。

#include <vector>
#include <queue>
using namespace std;

const int INF = 0x3f3f3f3f;

struct Edge {
int vertex, weight;
};

class Graph {
private:
int n;
vector<Edge> * edges;
bool * visited;
public:
int * dist;
Graph (int input_n) {
n = input_n;
edges = new vector<Edge>[n];
dist = new int[n];
visited = new bool[n];
memset(visited, 0, n);
memset(dist, 0x3f, n * sizeof(int));
}
~Graph() {
delete[] dist;
delete[] edges;
delete[] visited;
}
void insert(int x, int y, int weight) {
edges[x].push_back(Edge{y, weight});
edges[y].push_back(Edge{x, weight});
}
void dijkstra(int v) {
//v是源点
dist[v]=0;
for(int i=0;i<n;i++){
int min_dist=INF,min_vertex;
for(int j=0;j<n;++j){
if(!visited[j]&&dist[j]<min_dist){
min_dist=dist[j];
min_vertex=j;
}
}
visited[min_vertex]=1;
//松弛操作
for(Edge &j:edges[min_vertex]){
//与min_vertex结点相连的结点遍历
//更新相邻点的最短距离
if(min_dist+j.weight<dist[j.vertex]){
dist[j.vertex]=min_dist+j.weight;
}
}
}

}
};

int main() {
int n, m;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
g.insert(a, b, c);
}
g.dijkstra(0);
for (int i = 0; i < n; i++) {
cout << i << ": " << g.dist[i] << endl;
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Kruskal 最小生成树 & Dijkstra 最短路径 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)