import java.util.*;
public class Main {
static class Pair implements Comparable<Pair>{
int vtx;
int cost;
@Override
public int compareTo(Pair o){
return o.cost-this.cost;
}
}
static void dijkstra(HashMap<Integer,Vertices> vtces, int src){
HashMap<Integer,Integer> ans=new HashMap<Integer,Integer>();
PriorityQueue<Pair> pq=new PriorityQueue<Pair>();
HashMap<Integer,Pair> map=new HashMap<>();
for(int key:vtces.keySet()){
Pair np=new Pair();
np.vtx=key;
np.cost=Integer.MAX_VALUE;
if(key==src){
np.cost=0;
}
//System.out.println(np.cost);
pq.add(np);
map.put(key,np);
}
while(!pq.isEmpty()){
Pair rp=pq.poll();
ans.put(rp.vtx,rp.cost);
map.remove(rp.vtx);
Set<Integer> adjs=vtces.get(rp.vtx).adj.keySet();
for(int nbr:adjs){
if(map.containsKey(nbr)){
int oc=map.get(nbr).cost;
int nc=rp.cost+vtces.get(rp.vtx).adj.get(nbr);
if(nc<oc){
Pair temp=map.get(nbr);
temp.cost=nc;
map.put(nbr,temp);
pq.add(temp);
}
}
}
}
for(int key:vtces.keySet()){
if(ans.containsKey(key)){
System.out.print(ans.get(key)+" ");
}
else{
System.out.print("-1 ");
}
}
}
static class Vertices{
HashMap<Integer,Integer> adj=new HashMap<Integer,Integer>();
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int e=sc.nextInt();
HashMap<Integer,Vertices> vtces=new HashMap<Integer,Vertices>();
for(int i=1;i<=n;i++){
vtces.put(i,new Vertices());
}
while(e-->0){
int u=sc.nextInt();
int v=sc.nextInt();
int wt=sc.nextInt();
Vertices vtx1=vtces.get(u);
Vertices vtx2=vtces.get(v);
vtx1.adj.put(v,wt);
vtx2.adj.put(u,wt);
}
int src=sc.nextInt();
dijkstra(vtces,src);
System.out.println();
}
}
}