Thursday, February 23, 2017

Dijkstra Algorithm - Implementation with C++

/*
Bismillahir Rahmanir Rahim
Dijkstra algorithm implementation(C++)
Shortest path for all nodes from given node
*/
#include<bits/stdc++.h>
#define fi(n, m) for(int i=n; i<=m; i++)
#define fd(n, m) for(int i=n; i>=m; i--)
using namespace std;
vector<int>vt[1009], cost[1009];
int dis[1009];

struct node{
    int u, w;
    node(int a, int b){
        u=a, w=b;
    }
    bool operator < (const node & p)const{
        return p.w<w;
    }
};

void dijkstra(int st){
    priority_queue<node>q;
    memset(dis, 63, sizeof(dis));
    dis[st]=0;
    q.push(node(st, 0));
    while(!q.empty()){
        node top=q.top();
        q.pop();
        int u=top.u;
        int sz=vt[u].size();
        fi(0, sz-1){
            int v=vt[u][i];
            if(dis[u]+cost[u][i]<dis[v]){
                dis[v]=dis[u]+cost[u][i];
                q.push(node(v, dis[v]));
            }
        }
    }
}

int main(){
    int n, e, u, v, w, m;
    cin>>n>>e;
    while(e--){
        cin>>u>>v>>w;
        vt[u].push_back(v);
        vt[v].push_back(u);
        cost[u].push_back(w);
        cost[v].push_back(w);
    }
    cin>>m;      // from this node
    dijkstra(m);
    fi(1, n)cout<<m<<" to "<<i<<" = "<<dis[i]<<endl;
    return 0;
}

No comments:

Post a Comment