#include <bits/stdc++.h>
using namespace std;
struct edge { int to, length; };
// The graph used in this example is at
// https://w...content-available-to-author-only...f.com/IOIPRAC/problems/INOI1402
// You can verify the distance calulated by this program is correct.
// Copied Dijsktra code
// Modified it to return a vector of shortest distance to
// all other nodes from source vertex
vector<int> dijkstra2(const vector< vector<edge> > &graph, int source) {
// ith position in min_distance
// stores the minimum distance from source to node i
vector<int> min_distance( graph.size(), INT_MAX );
min_distance[ source ] = 0;
// Active vertices - The vertices whose edges are not yet to be checked
set< pair<int,int> > active_vertices;
active_vertices.insert( {0,source} );
while (!active_vertices.empty()) {
int where = active_vertices.begin()->second;
// We don't have any specific target now so it's commented
// if (where == target) return min_distance[where];
active_vertices.erase( active_vertices.begin() );
for (auto ed : graph[where])
// If new distance is less than the orignal distance
if (min_distance[ed.to] > min_distance[where] + ed.length) {
active_vertices.erase( { min_distance[ed.to], ed.to } );
// Stores the shorter distance from source to this vertex
// which just got covered in active_vertices
min_distance[ed.to] = min_distance[where] + ed.length;
// Insert head node of the new edge which just got covered now
active_vertices.insert( { min_distance[ed.to], ed.to } );
}
}
return min_distance;
}
int main()
{
ios_base::sync_with_stdio(false);
int n, m, k, tail, head, cost;
cin >> n >> m;
vector< vector<edge> > graph;
vector<edge> heads;
for(int i = 0; i < n + 1; i++)
{
heads.clear();
graph.push_back(heads);
}
for(int i = 0; i < m; i++)
{
cin >> tail >> head >> cost;
edge e;
e.length = cost;
e.to = head ;
graph[tail].push_back(e);
e.to = tail;
graph[head].push_back(e);
}
// The graph used in this example is at
// https://w...content-available-to-author-only...f.com/IOIPRAC/problems/INOI1402
// You can verify the distance calulated by this program is correct.
vector<int> dist = dijkstra2(graph, 1);
for(vector<int>::iterator it = dist.begin()+1; it != dist.end(); it++)
// Used begin() + 1 since there is no node 0 in the graph
// as begin() would point to 0th index
cout << "Shortest Distance from 1 to " << it - dist.begin() << " is " << *it << endl;
return 0;
}