-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.cpp
73 lines (71 loc) · 1.83 KB
/
dijkstra.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
#define INDEX 1 //set this to 1 if graph input starts with 1 as first node.
//#define UNDIRECTED // define this to process the input for undirected graph test case
using std::vector;
using std::queue;
using std::pair;
using std::priority_queue;
class Compare
{
public:
bool operator()(pair<int, int> a, pair<int, int> b)
{
return a.second > b.second;
}
};
int distance(vector<vector<int> > &adj, vector<vector<double> > &cost, int s,
int t)
{
//write your code her
vector<double> dist(adj.size(), INFINITY);
priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> p;
p.push(std::make_pair(s, 0));
dist[s] = 0;
vector<bool> visited(adj.size(), 0);
while (!p.empty())
{
int n = p.top().first;
p.pop();
if (visited[n])
continue;
for (int i = 0; i < adj[n].size(); i++)
{
if (dist[adj[n][i]] > (dist[n] + cost[n][i])) //Relax
{
dist[adj[n][i]] = (dist[n] + cost[n][i]);
p.push(std::make_pair(adj[n][i], dist[adj[n][i]]));
}
}
visited[n] = true;
}
if (dist[t] != INFINITY)
return dist[t];
else
return -1;
}
int main()
{
int n, m;
std::cin >> n >> m;
vector < vector<int> > adj(n, vector<int>());
vector < vector<double> > cost(n, vector<double>());
for (int i = 0; i < m; i++)
{
int x, y, w;
std::cin >> x >> y >> w;
adj[x - INDEX].push_back(y - INDEX);
cost[x - INDEX].push_back(w);
#ifdef UNDIRECTED
adj[y - INDEX].push_back(x - INDEX);
cost[y - INDEX].push_back(w);
#endif
}
int s, t;
std::cin >> s >> t;
s = s - INDEX;
t = t - INDEX;
std::cout << distance(adj, cost, s, t);
}