// Arup Guha
// 3/7/2022
// Solution to 2021 SER D1/D2 Problem: Tree Hopping
// This solution doesn't use binary lifting; just general logic with depth/parent information.

import java.util.*;
import java.io.*;

public class treehopping {

	public static int n;
	public static int[] depth;
	public static ArrayList<Integer>[] kids;
	public static int[] parent;

	public static void main(String[] args) throws Exception {

		// Get # of cases.
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		int nC = Integer.parseInt(stdin.readLine());
		
		// Store all answers here.
		StringBuffer sb = new StringBuffer();
		
		// Process cases.
		for (int loop=0; loop<nC; loop++) {
		
			// Set up tree.
			n = Integer.parseInt(stdin.readLine().trim());
			depth = new int[n];
			kids = new ArrayList[n];
			parent = new int[n];
			for (int i=0; i<n; i++) 
				kids[i] = new ArrayList<Integer>();
			
			// Read in edges.
			for (int i=1; i<n; i++) {
				StringTokenizer tok = new StringTokenizer(stdin.readLine());
				int v1 = Integer.parseInt(tok.nextToken())-1;
				int v2 = Integer.parseInt(tok.nextToken())-1;
				kids[v1].add(v2);
				kids[v2].add(v1);
			}

			// Form our tree.
			makeTree(0);
			
			// Read in permutation.
			int[] perm = new int[n];
			for (int i=0; i<n; i++)
				perm[i] = Integer.parseInt(stdin.readLine())-1;

			// Final answer.
			sb.append(check(perm)+"\n");
		}
		
		// Ta da!
		System.out.print(sb);
	}
	
	public static int check(int[] perm) {
		
		// Try each pair.
		for (int i=0; i<n-1; i++) {
			
			int a = perm[i];
			int b = perm[i+1];
			// Easiest case.
			if (Math.abs(depth[a] - depth[b]) > 3) return 0;
			
			// If at same depth, only works if we go 1 up.
			if (depth[a] == depth[b]) { 
				if (parent[a] == parent[b]) continue;
				return 0;
			}
			
			// One or the other has to climb...so do it and count.
			int cnt = 0;
			while (depth[a] > depth[b]) {
				a = parent[a];
				cnt++;
			}
			while (depth[b] > depth[a]) {
				b = parent[b];
				cnt++;
			}
			
			// 3 or less.
			if (a == b) continue;
			
			// Don't have time to climb.
			if (cnt > 1) return 0;
			
			// This doesn't work.
			if (parent[a] != parent[b]) return 0;
		}
		
		// If we make it here, we're good.
		return 1;
	}

	public static void makeTree(int root) {

		// Set up BFS.
		ArrayDeque<Integer> q = new ArrayDeque<Integer>();
		q.offer(root);
		parent[root] = -1;
		depth[root] = 0;

		// Run BFS.
		while (q.size() > 0) {

			root = q.poll();

			// Remove the parent from the kid list.
			if (parent[root] != -1) kids[root].remove( (Integer)parent[root] );

			// Enqueue the kids.
			for (int i=0; i<kids[root].size(); i++) {
				int next = kids[root].get(i);
				q.offer(next);
				parent[next] = root;
				depth[next] = depth[root]+1;
			}
		}
	}
}