Problem Link: https://onlinejudge.org/external/109/10986.pdf
Note: This problem is a straightforward application of the standard Dijkstra algorithm.
Code:
#include <bits/stdc++.h>
#define MAX 100005
#define INF INT_MAX
#define pii pair<int,int>
/*----------------------Graph Moves----------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*------------------------------------------------*/
using namespace std;
int dijkstra(int src, int dst, vector<vector<pii>> &adj)
{
vector<int> dis(MAX, INF);
//dis[100005]={INT_MAX} ; why doesn't work(gives wrong answer) I don't know!
dis[src]=0;
priority_queue<pii, vector<pii>, greater<pii> >pq;
pq.push({0, src}); // Insert source in priority queue and initialize its distance as 0.
while(!pq.empty())
{
int u=pq.top().second;
int cost=pq.top().first;
pq.pop();
//Optimization in the priority queue:
/*
Ideally, for updating the priority queue, we must delete the old value and reinsert with the
new cost value. But, as we know that the updated cost value is always lesser than the old
value and would be popped from the queue and visited before the old value,
we could save time and avoid removing the old value from the queue.
*/
if(dis[u]<cost) continue;
for(int i=0; i<adj[u].size(); i++)
{
int v=adj[u][i].first;
cost=adj[u][i].second;
if(dis[v]>dis[u]+cost)
{
dis[v]=dis[u]+cost;
pq.push({dis[v], v});
}
}
}
return dis[dst];
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int t;
cin>>t;
for(int z=1; z<=t; z++)
{
int node,edge,src,dst;
cin>>node>>edge>>src>>dst;
if(edge==0)
{
cout<<"Case #"<<z<<": unreachable"<<endl;
continue;
}
vector<vector<pair<int,int> > > adj(node+1);
for(int i=0; i<edge; i++)
{
int from,to,cost;
cin>>from>>to>>cost;
adj[from].push_back({to, cost});
adj[to].push_back({from, cost});
}
int min_distace=dijkstra(src, dst, adj);
if(min_distace!=INT_MAX)
{
cout<<"Case #"<<z<<": "<<min_distace<<endl;
}
else
{
cout<<"Case #"<<z<<": unreachable"<<endl;
}
}
return 0;
}