#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Maximum number of nodes
const int MaxN = 1 + 1e2 ;
// Infinite distance used to represent unreachable nodes
const ll INF = 1e18 ;
int n, m, s; // n = number of nodes, m = number of edges, s = source node
bool mark[ MaxN] ; // mark array to check if a node has been processed
ll dist[ MaxN] ; // Array to store the shortest distance from the source to each node
vector< pair< int , int >> adj[ MaxN] ; // Adjacency list to store the graph. Each pair represents (destination node, edge weight)
void Dijkstra( int s) {
// Initialize all distances as INF (unreachable), except the source node which is 0
fill( dist + 1 , dist + n + 1 , INF) ;
dist[ s] = 0 ; // Distance to the source node is always 0
// Priority queue (min-heap) for selecting the node with the smallest distance
// The pair consists of (distance, node)
priority_queue< pair< ll, int > , vector< pair< ll, int >> , greater< pair< ll,int >>> pq;
pq.push ( { 0 , s} ) ; // Push the source node with distance 0 into the priority queue
while ( ! pq.empty ( ) ) {
int u = pq.top ( ) .second ; // Get the node with the smallest distance
pq.pop ( ) ;
// If the node is already processed, skip it
if ( mark[ u] ) continue ;
mark[ u] = true ; // Mark the node as processed
// Process all neighbors of the current node
for ( auto e : adj[ u] ) {
int v = e.first ; // Neighbor node
ll w = e.second ; // Weight of the edge connecting u and v
// If the new distance through node u is shorter, update the distance to node v
if ( dist[ v] > dist[ u] + w) {
dist[ v] = dist[ u] + w; // Update the shortest distance to node v
pq.push ( { dist[ v] , v} ) ; // Push the updated distance and node into the priority queue
}
}
}
}
int main( ) {
// Read number of nodes, edges, and the source node
cin >> n >> m >> s;
// Read the edges (u, v, w) and populate the adjacency list
for ( int i = 0 ; i < m; ++ i) {
int u, v, w;
cin >> u >> v >> w;
adj[ u] .push_back ( { v, w} ) ; // Add the edge u -> v with weight w to the adjacency list
}
// Run Dijkstra's algorithm to find the shortest path from source s
Dijkstra( s) ;
// Print the shortest distances to all nodes from the source
for ( int i = 1 ; i <= n; ++ i) {
// If a node is unreachable (distance is INF), print -1
if ( dist[ i] == INF) cout << - 1 << endl;
else cout << dist[ i] << endl; // Other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