package arupsClassFinalTeam;

import java.util.Arrays;
import java.util.Scanner;

public class BubblersDavidSol {

	public static void main(String[] args) {
		Scanner fs=new Scanner(System.in);
		int T=fs.nextInt();
		for (int tt=0; tt<T; tt++) {
			int n=fs.nextInt(), m=fs.nextInt();
			DisjointSet dj=new DisjointSet(n);
			Edge[] edges=new Edge[m];
			for (int i=0; i<m; i++) edges[i]=new Edge(fs.nextInt()-1, fs.nextInt()-1, fs.nextInt());
			Arrays.sort(edges);
			Edge[] taken=new Edge[n-1];
			int takenInd=0;
			for (Edge e:edges)
				if (dj.union(e.a, e.b)) taken[takenInd++]=e;
			if (takenInd<n-1) {
				System.out.println(-1);
				continue;
			}
			int ans=0;
			for (Edge e:taken)
				ans=Math.max(ans, e.c)+1;
			System.out.println(ans);
		}
	}

	static class Edge implements Comparable<Edge> {
		int a, b, c;
		public Edge(int a, int b, int c) {
			this.a=a;
			this.b=b;
			this.c=c;
		}
		public int compareTo(Edge o) {
			return Integer.compare(c, o.c);
		}
	}
	
	static class DisjointSet {
		int[] s;
		
		public DisjointSet(int n) {
			Arrays.fill(s = new int[n], -1);
		}
		
		public int find(int i) {
			return s[i] < 0 ? i : (s[i] = find(s[i]));
		}
		
		public boolean union(int a, int b) {
			if ((a = find(a)) == (b = find(b))) return false;
			if(s[a] == s[b]) s[a]--;
			if(s[a] <= s[b]) s[b] = a; else s[a] = b;
			return true;
		}
	}
	
}
