Codeforces will not be available in the period 01:00-05:00 May, 30 (MSK, UTC +3) because of maintenance. ×

n8118's blog

By n8118, history, 5 years ago, In English,

I have learnt Dijkstra's recently and couldn't implement it effectively. Can some one post your Dijkstra's algo implementation in (c or c++) using stl's. I will use it as reference to implement my code. Thanks in advance..

 
 
 
 
  • Vote: I like it
  • +1
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Hello, You can try this question : EZDIJKST, it's a direct implementation of the algorithm. You can refer My Solution which uses STL set for reference.

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This is my typical implementation of Dijkstra using C++11 and priority_queue: Dijkstra (this code finds the shortest path from node 1 to all other nodes)

  • »
    »
    2 months ago, # ^ |
      Vote: I like it -8 Vote: I do not like it

    why you use if(dis>d[u]) continue?

    • »
      »
      »
      7 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Because otherwise it would simply be a BFS that keeps going only when new distance would be lower than current minimum distance for the node, and that would be very slow in most cases.

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it
»
22 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Hello!

First of all, I would suggest you to write your own version of the code (for testing you have 20C — Dijkstra? problem here on Codeforces), because you will learn how the algorithm works and how to use it. However I will give you my code :). Keep in mind you can find more versions of Dijkstra on geekforgeeks, e-maxx, youtube, ...

Here is my Dijkstra template: https://github.com/Sprdalo/Compete/blob/master/dijkstra.sublime-snippet

To see how to use it go to my submit for this problem which is given here.

»
11 months ago, # |
  Vote: I like it -8 Vote: I do not like it

Checked with C. Dijkstra?.

#include <bits/stdc++.h>
using namespace std;

#define debug(x) cout<<#x<<" is "<<endl

using ll = long long;

#define x first
#define y second

template <typename T>
struct Dijkstra {

	int node,edge;
	vector< vector< pair<int,T> > > adj;
	vector< T > level;
	vector<int> parent;

	Dijkstra(int _node, int _edge) : node(_node), edge(_edge) {
		vector<int>(node+1).swap(parent);
		vector<T>(node+1, numeric_limits<T>::max()).swap(level);
		vector< vector< pair<int,T> > > (node+1).swap(adj);
	}

	void add_edge(int u, int v, T w) {
		adj[u].push_back({v,w});
		adj[v].push_back({u,w});
	}

	void traverse(int src) {

		level[src] = 0;
		set< pair<T,int> > s {{0,src}};
		parent[src] = -1;

		while(not s.empty()) {
			auto it = *s.begin();
			int cur_node = it.y;
			T cur_level = it.x;
			s.erase(s.begin());

			for(auto u : adj[cur_node]) {
				if(level[u.x] - u.y > cur_level) {
					level[u.x] = cur_level + u.y;
					parent[u.x] = cur_node; 
					s.insert({level[u.x],u.x});
				}
			}
		}
	}

	void print_path(int x) {

		if(level[x] == numeric_limits<T>::max()) {
			cout<<"-1\n";
			return;
		}

		if(x == -1){
			return;
		}

		print_path(parent[x]);
		cout<<x<<" ";

	}

};


int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);


	int node,edge;
	cin>>node>>edge;

	Dijkstra<ll> d(node,edge);


	while(edge--){
		int x,y;
		ll w;
		cin>>x>>y>>w;
		d.add_edge(x,y,w);
	}

	d.traverse(1);
	d.print_path(node);

	return 0;
}
  • »
    »
    7 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    Suggest you to put the code into the spoiler
»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

https://github.com/okwedook/olymp/blob/master/Dijkstra.cpp

This is an actually fast and memory efficient (and also veeery short) implementation. It uses a few template features I use, but you can look at template.cpp in the same repo.

  • »
    »
    7 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks for your solution, I dont know I can take the path like that. But can I ask this question

    If we only need to calculate the distance without taking the path. Is this the optimized code or we can still improve it ?

    My code
    • »
      »
      »
      7 weeks ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      Your code uses pairs to store the set. It does actually increase memory usage (I'm only storing the indices) and time usage (as you are also comparing pairs, while I do only one comparison), But you should test your code, it seems pretty neat.

      • »
        »
        »
        »
        7 weeks ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        What is "neat". Is it mean it is almost similar ?

        • »
          »
          »
          »
          »
          7 weeks ago, # ^ |
            Vote: I like it +1 Vote: I do not like it

          It's good in my opinion.

          • »
            »
            »
            »
            »
            »
            7 weeks ago, # ^ |
            Rev. 2   Vote: I like it 0 Vote: I do not like it

            How about prim algorithm. How do you implement without using heap of pair ?

            prim()
            • »
              »
              »
              »
              »
              »
              »
              7 weeks ago, # ^ |
                Vote: I like it +1 Vote: I do not like it

              You can use the same idea as used in my Dijkstra imple. Just store the indices of unused vertices and compare them using a custom comparator.

»
7 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it
Dijkstra - priority_queue implementation
Dijkstra - Set implementation
SPFA - Queue implementation