TheAlgorithms-C-Plus-Plus/graph/dijkstra.cpp

53 lines
1.4 KiB
C++
Raw Normal View History

#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
2017-10-14 00:07:47 +08:00
using namespace std;
2017-10-14 05:25:53 +08:00
#define INF 10000010
2019-08-21 10:10:08 +08:00
vector<pair<int, int>> graph[5 * 100001];
int dis[5 * 100001];
int dij(vector<pair<int, int>> *v, int s, int *dis) {
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>>
pq;
// source distance to zero.
2019-08-21 10:10:08 +08:00
pq.push(make_pair(0, s));
2017-10-14 00:07:47 +08:00
dis[s] = 0;
int u;
while (!pq.empty()) {
2017-10-14 00:07:47 +08:00
u = (pq.top()).second;
pq.pop();
for (vector<pair<int, int>>::iterator it = v[u].begin();
it != v[u].end(); it++) {
if (dis[u] + it->first < dis[it->second]) {
2017-10-14 00:07:47 +08:00
dis[it->second] = dis[u] + it->first;
2019-08-21 10:10:08 +08:00
pq.push(make_pair(dis[it->second], it->second));
2017-10-14 00:07:47 +08:00
}
}
}
}
int main() {
2019-08-21 10:10:08 +08:00
int m, n, l, x, y, s;
// n--> number of nodes , m --> number of edges
2019-08-21 10:10:08 +08:00
cin >> n >> m;
for (int i = 0; i < m; i++) {
// input edges.
2019-08-21 10:10:08 +08:00
scanf("%d%d%d", &x, &y, &l);
graph[x].push_back(make_pair(l, y));
graph[y].push_back(
make_pair(l, x)); // comment this line for directed graph
2017-10-14 00:07:47 +08:00
}
// start node.
2019-08-21 10:10:08 +08:00
scanf("%d", &s);
// intialise all distances to infinity.
for (int i = 1; i <= n; i++) dis[i] = INF;
2019-08-21 10:10:08 +08:00
dij(graph, s, dis);
for (int i = 1; i <= n; i++)
if (dis[i] == INF)
cout << "-1 ";
2017-10-14 05:25:53 +08:00
else
2019-08-21 10:10:08 +08:00
cout << dis[i] << " ";
2017-10-14 05:25:53 +08:00
return 0;
2017-10-14 00:07:47 +08:00
}