package com.company.real;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
/*
2
4 3 2
1 2 2 1
2 3 3 4
3 4 5 4
2 1 2
1 2 5 7
*/
//SW练习_pro20200109_小石头游戏_拓扑排序
public class P20200109 {
static int[] in;
//static int[] out;
static List<Integer>[] f;//list[i].get(j) 保存的是第i个节点链接的第j个点的编号
public static void main(String[] args) throws Exception{
//System.setIn(new FileInputStream("C:\\Users\\XAGDC\\Desktop\\sw\\PRO\\47 Pro 小石头游戏 The Pebble Game\\sample_input.txt"));
System.setIn(new FileInputStream("C:\\Users\\XAGDC\\Desktop\\sw\\PRO\\47 Pro 小石头游戏 The Pebble Game\\eval_input.txt"));
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(reader.readLine());
int T=Integer.parseInt(st.nextToken());
for (int zz = 0; zz <T ; zz++) {
List<Integer> res=new ArrayList<>();
st=new StringTokenizer(reader.readLine());
int N=Integer.parseInt(st.nextToken());//石子的个数
int M=Integer.parseInt(st.nextToken());//线的个数
int K=Integer.parseInt(st.nextToken());//第几个石子
f=new List[N+1];
in=new int[N+1];
//out=new int[N+1];
PriorityQueue<Integer> pq=new PriorityQueue();//用来存没有入度的点
for (int i = 1; i <=N ; i++) {
f[i]=new ArrayList();
f[i].add(0);
}
long sum=0;
for (int i = 0; i <M ; i++) {
st=new StringTokenizer(reader.readLine());
int a=Integer.parseInt(st.nextToken());//点1的编号
int b=Integer.parseInt(st.nextToken());//点2的编号
int p=Integer.parseInt(st.nextToken());//点1的分数
int q=Integer.parseInt(st.nextToken());//点2的分数
if(p>q){//p->q a->b
//out[a]++;
in[b]++;
f[a].add(b);
sum=sum+p;
}else if(p<q){//q->p b->a
//out[b]++;
in[a]++;
f[b].add(a);
sum=sum+q;
}else{
sum=sum+q;
}
}
for (int i = 1; i <=N ; i++) {
if(in[i]==0){//找到入度为0的节点
pq.add(i);
}
}
while(!pq.isEmpty()){
int c=pq.poll();//取出当前节点
res.add(c);
//for (int i = 1; i <=out[c] ; i++) {//这个点的连接节点入度-1
for (int i = 1; i <f[c].size() ; i++) {//这个点的连接节点入度-1
in[f[c].get(i)]--;
if(in[f[c].get(i)]==0){//如果减完后,这个点入度为0了
pq.add(f[c].get(i));
}
}
}
System.out.printf("#%d %d %d\n",(zz+1),sum,res.get(K-1));
}
reader.close();
}
}