Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <limits>
- using std::cout;
- using std::cin;
- using std::vector;
- using std::pair;
- using std::endl;
- using std::greater;
- using std::numeric_limits;
- using std::priority_queue;
- long long dijkstra ( vector<vector<pair<int, long long>>> graph, int source, int destination );
- void addEdge ( vector<vector<pair<int, long long>>> &graph, int u, int v, int weight );
- bool sortByWeight ( const pair<int,int> &p1, const pair<int,int> &p2 );
- int main ( void )
- {
- // freopen("input.txt", "r", stdin);
- // freopen("output.txt", "w", stdout);
- /// Edges nodi, Vertices nodi
- int vertices, edges;
- cin >> vertices >> edges;
- int source, destination;
- cin >> source >> destination;
- vector<vector<pair<int, long long>>> graph ( vertices );
- for ( int i = 0; i < edges; i++ ) {
- int u, v, weight;
- cin >> u >> v >> weight;
- addEdge( graph, u - 1, v - 1, weight );
- }
- cout << dijkstra ( graph, source - 1, destination - 1 ) << endl;
- return 0;
- }
- long long dijkstra ( vector<vector<pair<int, long long>>> graph, int source, int destination ) {
- vector <bool> visited ( graph.size(), false );
- vector <long long> distances ( graph.size(), numeric_limits<long long>::max() );
- priority_queue< pair<int, long long>, vector <pair<int, long long>>, greater<pair<int, long long>> > pq;
- /// source -> source : 0
- distances [ source ] = 0;
- pq.push( pair<int, long long> ( source, distances [ source ] ) );
- while ( ! pq.empty() ) {
- int index = pq.top().first;
- int weight = pq.top().second;
- pq.pop();
- visited [ index ] = true;
- for ( pair<int, long long> &edge : graph [ index ] ) {
- if ( ! visited [ edge.first ] ) {
- long long distance = distances [ index ] + edge.second;
- if ( distance < distances [ edge.first ] ) {
- distances [ edge.first ] = distance;
- pq.push( pair<int, long long> ( edge.first, distances [ edge.first ] ) );
- }
- }
- }
- }
- return distances [ destination ];
- }
- void addEdge ( vector<vector<pair<int, long long>>> &graph, int u, int v, int weight ) {
- if ( u >= 0 && u < graph.size() ) {
- if ( v >= 0 && v < graph.size() ) {
- graph [ u ].push_back ( pair <int, int> ( v, weight ) );
- /// IF Undirected
- /// graph [ v ].push_back ( pair <int, int> ( u, weight ) );
- return;
- }
- }
- }
- bool sortByWeight ( const pair<int,int> &p1, const pair<int,int> &p2 ) {
- return ( p1.second < p2.second );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement