← Home
package main

import (
	"bufio"
	"fmt"
	"os"
)

type Edge struct {
	u, v int
}

type Path struct {
	u, v int
}

var adj [][]int
var cuts []Edge
var paths []Path

func dfs(u, p int) int {
	var active []int
	var active_v []int
	for _, v := range adj[u] {
		if v == p {
			continue
		}
		ep := dfs(v, u)
		if ep != 0 {
			active = append(active, ep)
			active_v = append(active_v, v)
		} else {
			cuts = append(cuts, Edge{u, v})
		}
	}

	if len(active) == 0 {
		return u
	} else if len(active) == 1 {
		return active[0]
	} else {
		paths = append(paths, Path{active[0], active[1]})
		for i := 2; i < len(active); i++ {
			cuts = append(cuts, Edge{u, active_v[i]})
			paths = append(paths, Path{active_v[i], active[i]})
		}
		return 0
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 10*1024*1024)

	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	scanInt := func() int {
		scanner.Scan()
		res := 0
		for _, b := range scanner.Bytes() {
			res = res*10 + int(b-'0')
		}
		return res
	}

	if !scanner.Scan() {
		return
	}
	t := 0
	for _, b := range scanner.Bytes() {
		t = t*10 + int(b-'0')
	}

	adj = make([][]int, 0)

	for i := 0; i < t; i++ {
		n := scanInt()
		if cap(adj) < n+1 {
			adj = make([][]int, n+1)
		} else {
			adj = adj[:n+1]
			for j := 0; j <= n; j++ {
				adj[j] = adj[j][:0]
			}
		}

		for j := 0; j < n-1; j++ {
			u := scanInt()
			v := scanInt()
			adj[u] = append(adj[u], v)
			adj[v] = append(adj[v], u)
		}

		if cap(cuts) < n {
			cuts = make([]Edge, 0, n)
		}
		cuts = cuts[:0]

		if cap(paths) < n+1 {
			paths = make([]Path, 0, n+1)
		}
		paths = paths[:0]

		ep := dfs(1, 0)
		if ep != 0 {
			paths = append(paths, Path{1, ep})
		}

		fmt.Fprintln(writer, len(cuts))
		for j := 0; j < len(cuts); j++ {
			fmt.Fprintf(writer, "%d %d %d %d\n", cuts[j].u, cuts[j].v, paths[j].v, paths[j+1].u)
		}
	}
}