diff --git a/Intermediate/CPP/problem_52.cpp b/Intermediate/CPP/problem_52.cpp new file mode 100644 index 0000000..85c5ec2 --- /dev/null +++ b/Intermediate/CPP/problem_52.cpp @@ -0,0 +1,47 @@ +/*Dijkastra Algorithm*/ +//Solved by aryangupta02092002 + +#include +using namespace std; + +int main() +{ + int n, m, src; + cin>>n>>m>>src; + + vector> g[n+1]; + int a, b, wt; + for(int i=0; i>a>>b>>wt; + g[a].push_back(make_pair(b, wt)); + g[b].push_back(make_pair(a, wt)); + } + + priority_queue, vector>, greater>> pq; + vector distTo(n+1, INT_MAX); + distTo[src] = 0; + pq.push(make_pair(0, src)); + + while(!pq.empty()){ + int dist = pq.top().first; + int prev = pq.top().second; + pq.pop(); + + vector> :: iterator it; + for(it=g[prev].begin(); it!=g[prev].end(); it++){ + int next = it->first; + int nextDist = it->second; + + if(distTo[next] > distTo[prev] + nextDist){ + distTo[next] = distTo[prev] + nextDist; + pq.push(make_pair(distTo[next], next)); + } + } + + } + cout<<"Distance from source "<