Last active
August 29, 2015 14:06
-
-
Save poseidon4o/bb4fdbe2731988e1cb23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <queue> | |
#include <vector> | |
#include <algorithm> | |
#include <map> | |
#include <limits> | |
#include <iostream> | |
using namespace std; | |
typedef pair<int, int> weight_pair; | |
// Use custom comparator because default will compare pair::second when pair::first are equal | |
class weight_comapre { | |
public: | |
bool operator() (const weight_pair & left, const weight_pair & right) const { | |
return left.first < right.first; | |
} | |
}; | |
class Graph{ | |
vector<vector<int> > data; | |
public: | |
Graph(int size) { | |
data.resize(size); | |
for_each(begin(data), end(data), [&size](vector<int> & row) { | |
row.resize(size); | |
fill(begin(row), end(row), 0); | |
}); | |
} | |
int get_size() const { | |
return data.size(); | |
} | |
void add_edge(int x, int y, int weight) { | |
data[x][y] = weight; | |
} | |
int get_weigth(int x, int y) const { | |
return data[x][y]; | |
} | |
int dijkstra_path(int from, int to) { | |
vector<int> distances(get_size(), std::numeric_limits<int>::max()); | |
priority_queue<weight_pair, vector<weight_pair>, weight_comapre> que; | |
que.push(weight_pair(0, from)); | |
while(!que.empty()) { | |
weight_pair top = que.top(); | |
que.pop(); | |
for(int c = 0; c < get_size(); ++c) { | |
int weight = get_weigth(top.second, c); | |
if(weight && distances[c] > top.first + weight) { | |
distances[c] = top.first + weight; | |
que.push(weight_pair(distances[c], c)); | |
} | |
} | |
} | |
return distances[to] == std::numeric_limits<int>::max() ? -1 : distances[to]; | |
} | |
}; | |
int main() { | |
int size, edges; | |
cin >> size >> edges; | |
Graph graph(size + 1); // assuming nodes are 1 indexed | |
int x, y, weight; | |
for(int c = 0; c < edges; ++c) { | |
cin >> x >> y >> weight; | |
graph.add_edge(x, y, weight); | |
// assuming directed graph so add only one way edges | |
// graph.add_edge(y, x, weight); | |
} | |
int from, to; | |
cin >> from >> to; | |
cout << graph.dijkstra_path(from, to) << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment