import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner scn = new Scanner(System.in);
int T = scn.nextInt();
while(T-- != 0)
{
//no. of nodes
int n = scn.nextInt();
//no. of edges
int m = scn.nextInt();
//undirectd weighted graph
HashMap <Integer, HashMap <Integer, Integer>> graph = new HashMap <> ();
for(int i = 1; i<=n; i++)
graph.put(i, new HashMap <Integer, Integer> ());
for(int i = 1; i<=m ; i++)
{
int x = scn.nextInt();
int y = scn.nextInt();
int cost = scn.nextInt();
graph.get(x).put(y, cost);
graph.get(y).put(x, cost);
}
//source
int src = scn.nextInt();
dijkstraAlgo(graph, n, src);
System.out.println();
}
}
public static class Pair
{
//vertex name
int vname;
//min. distance or cost
//till that vertex
int cost;
Pair(int vname, int cost)
{
this.vname = vname;
this.cost = cost;
}
}
public static void dijkstraAlgo(HashMap <Integer, HashMap <Integer, Integer>> graph, int n, int src)
{
HashMap <Integer, Integer> finalAns = new HashMap <> ();
HashMap <Integer, Pair> map = new HashMap <> ();
PriorityQueue <Pair> pq = new PriorityQueue<> ((n1,n2) -> n1.cost - n2.cost);
for(int i = 1; i<=n; i++)
{
Pair p = new Pair(i,Integer.MAX_VALUE);
if(i == src)
{
p.cost = 0;
}
pq.add(p);
map.put(i,p);
}
while(!pq.isEmpty())
{
//removed pair
Pair rp = pq.remove();
finalAns.put(rp.vname,rp.cost);
for(int nbr : graph.get(rp.vname).keySet())
{
if(finalAns.containsKey(nbr))
continue;
Pair gp = map.get(nbr);
//old cost
int oc = gp.cost;
//new cost
int nc = rp.cost + graph.get(rp.vname).get(gp.vname);
if(nc < oc)
{
gp.cost = nc;
pq.remove(gp);
pq.add(gp);
}
}
}
for(int i = 1; i<=n; i++)
{
if(i == src)
continue;
if(finalAns.get(i) == Integer.MAX_VALUE)
System.out.print("-1 ");
else
System.out.print(finalAns.get(i) + " ");
}
}
}