import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        int t = nextInt();
        for (int q = 0; q < t; q++) {
            int n = nextInt();
            int m = nextInt();
            TreeMap<Integer, String> tm = new TreeMap<>();
            for (int i = 0; i < n; i++) {
                String s = "";
                int key = -1;
                for (int j = 0; j < m; j++) {
                    if (j == 0) {
                        key = nextInt();
                        s += Integer.toString(key) + " ";
                    } else {
                        s += Integer.toString(nextInt()) + " ";
                    }
                }
                tm.put(key, s);
            }
            int[] ind = new int[n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int h = nextInt();
                    if (tm.containsKey(h)) ind[j] = h;
                }
            }
            for (int i = 0; i < n; i++) {
                pw.println(tm.get(ind[i]));
            }
        }
        pw.close();

    }

    static long mod = 1_000_000_007;

    static StringTokenizer st = new StringTokenizer("");
    static BufferedReader br;

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}


import sun.reflect.generics.tree.Tree;

import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        int t = nextInt();
        for (int q = 0; q < t; q++) {
            int n = nextInt();
            int m = nextInt();
            TreeMap<Integer, String> tm = new TreeMap<>();
            int keys[] = new int[n];
            for (int i = 0; i < n; i++) {
                String s = "";
                int key = -1;
                for (int j = 0; j < m; j++) {
                    if (j == 0) {
                        key = nextInt();
                        s += Integer.toString(key) + " ";
                    } else {
                        s += Integer.toString(nextInt()) + " ";
                    }
                }
                tm.put(key, s);
                keys[i] = key;
            }
            int ind[] = new int[n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int h = nextInt();
                    if (tm.containsKey(h)) ind[j] = h;
                }
            }
            for (int i = 0; i < n; i++) {
                pw.println(tm.get(ind[i]));
            }
        }
        pw.close();

    }

    static long mod = 1_000_000_007;

    static StringTokenizer st = new StringTokenizer("");
    static BufferedReader br;

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}

class Path {
    int vertex, dist;

    public Path(int vertex, int dist) {
        this.vertex = vertex;
        this.dist = dist;
    }
}

class Edge {
    int a, b, c;

    public Edge(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}


import java.util.*;
import java.io.*;

public class B{
	public static void main(String[] args)  throws IOException,NumberFormatException{
		try {
		FastScanner sc=new FastScanner();
		PrintWriter out=new PrintWriter(System.out);
		int t=sc.nextInt();
		while(t-->0) {
			int n=sc.nextInt(),m=sc.nextInt();
			int a[][]=new int[n][m];
			int b[][]=new int[m][n];
			Map<Integer,Integer> pam=new HashMap<>();
			Map<Integer,Integer> map=new HashMap<>();
			int c[][]=new int[n][m];
			for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
					a[i][j]=sc.nextInt();
					map.put(a[i][j],j);
				}
			}
			for(int i=0;i<m;i++) {
				for(int j=0;j<n;j++) {
					b[i][j]=sc.nextInt();
					pam.put(b[i][j], j);
				}
			}
			for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
//					System.out.println(pam.get(a[i][j])+" "+map.get(a[i][j]));
					c[pam.get(a[i][j])][map.get(a[i][j])]=a[i][j];
				}
			}
			for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
					out.print(c[i][j]+" ");
				}
				out.println();
			}

		}
		out.close();
		}
		catch(Exception e) {
			return ;
		}

	}

	public static class Pair<L,R> {
	    private L l;
	    private R r;
	    public Pair(L l, R r){
	        this.l = l;
	        this.r = r;
	    }
	    public L getL(){ return l; }
	    public R getR(){ return r; }
	    public void setL(L l){ this.l = l; }
	    public void setR(R r){ this.r = r; }
	}

	static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;
		for(int i=0;i<n;i++) {
			int oi=random.nextInt(n),temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	public static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
                                      st=new StringTokenizer(br.readLine());
                              } catch (IOException e) {}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}

		long[] readLongArray(int n) {
			long[] a=new long[n];
			for(int i=0; i<n ; i++) a[i]=nextLong();
			return a;
		}

		String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
	}

}


import java.io.DataInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.xml.crypto.dsig.spec.HMACParameterSpec;
import java.util.Scanner;
import java.util.*;
public class Main {
    static
    Parser s = new Parser(System.in);
    static PrintWriter pw = new PrintWriter(System.out);
    static void sol() {
        HashMap<Long, Integer> nums = new HashMap<>();
        int n = s.nextInt(), m = s.nextInt();
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++) {
                long x = s.nextInt();
                nums.put(x, j);
            }
        }
        Long [][] a = new Long [n][m];
        int [] ans = new int [m];
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                a[j][i] = s.nextLong();
            }
            ans[nums.get(a[0][i])] = i;
        }

        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                pw.print(a[i][ans[j]] + " ");
            }
            pw.println();
        }
    }
    public static void main(String[] args) {
        int t = s.nextInt();
        for (int i = 0; i < t; i++) {
            sol();
        }
        pw.close();
    }
}

class Parser {
    final private int BUFFER_SIZE = 1 << 16;
    private DataInputStream din;
    private byte[] buffer;
    private int bufferPointer, bytesRead;

    public Parser(InputStream in) {
        din = new DataInputStream(in);
        buffer = new byte[BUFFER_SIZE];
        bufferPointer = bytesRead =  0;
    }
    public String nextString(int maxSize) {
        byte[] ch = new byte[maxSize];
        int point =  0;
        try {
            byte c = read();
            while (c == ' ' || c == '\n' || c=='\r')
                c = read();
            while (c != ' ' && c != '\n' && c!='\r') {
                ch[point++] = c;
                c = read();
            }
        } catch (Exception e) {}
        return new String(ch, 0,point);
    }
    public int nextInt() {
        int ret =  0;
        boolean neg;
        try {
            byte c = read();
            while (c <= ' ')
                c = read();
            neg = c == '-';
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');

            if (neg) return -ret;
        } catch (Exception e) {}
        return ret;
    }
    public long nextLong() {
        long ret =  0;
        boolean neg;
        try {
            byte c = read();
            while (c <= ' ')
                c = read();
            neg = c == '-';
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');

            if (neg) return -ret;
        } catch (Exception e) {}
        return ret;
    }
    private void fillBuffer() {
        try {
            bytesRead = din.read(buffer, bufferPointer =  0, BUFFER_SIZE);
        } catch (Exception e) {}
        if (bytesRead == -1) buffer[ 0] = -1;
    }

    private byte read() {
        if (bufferPointer == bytesRead) fillBuffer();
        return buffer[bufferPointer++];
    }
}
class pii{
    double x;
    double y;

    public pii(double x, double y) {
        this.x = x;
        this.y = y;
    }

}


import javax.xml.crypto.dsig.spec.HMACParameterSpec;
import java.util.Scanner;
import java.util.*;
public class Main {
    static
    Scanner s = new Scanner(System.in);
    static void sol() {
        HashMap<Long, Integer> nums = new HashMap<>();
        int n = s.nextInt(), m = s.nextInt();
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++) {
                long x = s.nextInt();
                nums.put(x, j);
            }
        }
        Long [][] a = new Long [n][m];
        int [] ans = new int [m];
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                a[j][i] = s.nextLong();
            }
            ans[nums.get(a[0][i])] = i;
        }
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                System.out.print(a[i][ans[j]] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        int t = s.nextInt();
        for (int i = 0; i < t; i++) {
            sol();
        }
    }
}

class pii{
    double x;
    double y;

    public pii(double x, double y) {
        this.x = x;
        this.y = y;
    }

}


import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;

public class Otbor {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);
        int t = Integer.parseInt(reader.readLine());
        for(int q = 0; q < t; ++q){
            StringTokenizer st = new StringTokenizer(reader.readLine());
            int n = Integer.parseInt(st.nextToken());
            int m = Integer.parseInt(st.nextToken());
            TreeMap<Integer, Integer> map = new TreeMap<>();
            ArrayList<Integer>[] str = new ArrayList[n];
            for(int i = 0; i < n; ++i){
                str[i] = new ArrayList<>();
            }
            for(int i = 0; i < n; ++i){
                st = new StringTokenizer(reader.readLine());
                for(int j = 0; j < m; ++j){
                    str[i].add(Integer.parseInt(st.nextToken()));
                }
                map.put(str[i].get(0), i);
            }
            TreeSet<Integer>[] stl = new TreeSet[m];
            ArrayList<Integer>[] stl2 = new ArrayList[m];
            for(int i = 0; i < m; ++i){
                stl[i] = new TreeSet<>();
                stl2[i] = new ArrayList<>();
            }
            for(int i = 0; i < m; ++i){
                st = new StringTokenizer(reader.readLine());
                for(int j = 0; j < n; ++j){
                    stl2[i].add(Integer.parseInt(st.nextToken()));
                    stl[i].add(stl2[i].get(stl2[i].size() - 1));
                }
            }
            int ind = -1;
            for(int i = 0; i < m; ++i){
                boolean check = true;
                for(int j = 0; j < n; ++j){
                    if(!stl[i].contains(str[j].get(0))){
                        check = false;
                        break;
                    }
                }
                if(check){
                    ind = i;
                    break;
                }
            }
            for(Integer k : stl2[ind]){
                StringBuilder s = new StringBuilder();
                int sr = map.get(k);
                for(int i = 0; i < m; ++i){
                    s.append(str[sr].get(i));
                    s.append(" ");
                }
                writer.println(s);
            }
        }
        writer.close();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[1000000][1000000];
int[][] b=new int[1000000][1000000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}

	t--;
}
out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
FastReader s=new FastReader();
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	int[][] a=new int[10000][m];
	int[][] b=new int[m][n];
	int e=-1;
	for(int i=0;i<n;i++) {
		int d=-1;
		for(int j=0;j<m;j++) {
			int c=s.nextInt();
			if(i==0 && j==0) {
				e=c;
			}
			if(j==0) {
				a[c][0]=c;
				d=c;
			}else {
				a[d][j]=c;
			}
		}
	}
	for(int i=0;i<m;i++) {
		for(int j=0;j<n;j++) {
			int c=s.nextInt();
		b[i][j]=c;
		}
	}
	int k=-1;
	for(int i=0;i<m;i++) {
		for(int j=0;j<n;j++) {
			if(b[i][j]==e) {
			k=i;
			break;
			}
		}
	}
	for(int i=0;i<n;i++) {
		for(int j=0;j<m;j++) {
			System.out.print(a[b[k][i]][j]+" ");
		}
		System.out.println();
	}
	t--;
}
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[10000000][10000000];
int[][] b=new int[10000000][10000000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}

	t--;
}
out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[1000][1000];
int[][] b=new int[1000][1000];
int[] p=new int[100000000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}

	t--;
}
out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
FastReader s=new FastReader();
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	int[][] a=new int[n][m];
	int[][] b=new int[m][n];
	int[] p=new int[n*m+1];
	for(int i=0;i<n;i++) {
		for(int j=0;j<m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=0;i<m;i++) {
		for(int j=0;j<n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
	System.out.print(a[p[b[0][i]]][j]+" ");
}
System.out.println();
	}
	t--;
}
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[1000000000][1000000000];
int[][] b=new int[1000000000][1000000000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}

	t--;
}
out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[1000][1000];
int[][] b=new int[1000][1000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}

	t--;
}
out.close();
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
FastReader s=new FastReader();
int[][] a=new int[1000][1000];
int[][] b=new int[1000][1000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	System.out.print(a[p[b[1][i]]][j]+" ");
}
System.out.println();
	}
	t--;
}
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 OutputStream outputStream =System.out;
		    PrintWriter out =new PrintWriter(outputStream);
FastReader s=new FastReader();
int[][] a=new int[1000][1000];
int[][] b=new int[1000][1000];
int[] p=new int[1000];
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	for(int i=1;i<=n;i++) {
		for(int j=1;j<=m;j++) {
			int v=s.nextInt();
			p[v]=i;
			a[i][j]=v;
		}
	}
	for(int i=1;i<=m;i++) {
		for(int j=1;j<=n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
	out.print(a[p[b[1][i]]][j]+" ");
}
out.println();
	}
	out.close();
	t--;
}
}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class asdasdasdasdad {
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
FastReader s=new FastReader();
int t=s.nextInt();
while(t>0) {
	int n=s.nextInt();
	int m=s.nextInt();
	int[][] a=new int[n][m];
	int[][] b=new int[m][n];
	HashMap<Integer,Integer> um=new HashMap<>();
	for(int i=0;i<n;i++) {
		for(int j=0;j<m;j++) {
			int v=s.nextInt();
			um.put(v, i);
			a[i][j]=v;
		}
	}
	for(int i=0;i<m;i++) {
		for(int j=0;j<n;j++) {
			b[i][j]=s.nextInt();
		}
	}
	for(int i=0;i<n;i++) {
int b1=um.get(b[0][i]);
for(int j=0;j<m;j++) {
	System.out.print(a[b1][j]+" ");
}
System.out.println();
	}
	t--;
}
}
}


import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;

import static java.lang.Math.max;
import static java.lang.Math.min;

public class B_Techno implements Runnable{

    // SOLUTION AT THE TOP OF CODE!!!
    // HACK ME PLEASE IF YOU CAN!!!
    // PLEASE!!!
    // PLEASE!!!
    // PLEASE!!!

    @SuppressWarnings("unused")
    private final static Random rnd = new Random();
    private final static String fileName = "";

    private final static long MODULO = 1000 * 1000 * 1000 + 7;

    // THERE SOLUTION STARTS!!!
    private void solve() {
        int t = readInt();
        while (t --> 0) {
            solveTest();
        }
    }

    void solveTest() {
        int rowsCount = readInt();
        int columnsCount = readInt();

        int[][] rows = readIntMatrixWithDecrease(rowsCount, columnsCount);
        int[][] columns = readIntMatrixWithDecrease(columnsCount, rowsCount);

        int size = rowsCount * columnsCount;

        int[] startedRows = new int[size];
        Arrays.fill(startedRows, -1);

        int[] startedColumns = new int[size];
        Arrays.fill(startedColumns, -1);

        for (int row = 0; row < rowsCount; ++row) {
            int first = rows[row][0];
            startedRows[first] = row;
        }

        for (int column = 0; column < columnsCount; ++column) {
            int first = columns[column][0];
            startedColumns[first] = column;
        }

        int topLeft = -1;
        for (int v = 0; v < size; ++v) {
            if (-1 != startedRows[v] && -1 != startedColumns[v]) {
                topLeft = v;
            }
        }

        int[][] answer = new int[rowsCount][];

        int[] firstColumn = columns[startedColumns[topLeft]];
        for (int i = 0; i < rowsCount; ++i) {
            int value = firstColumn[i];
            answer[i] = rows[startedRows[value]];
        }

        for (int[] row : answer) {
            for (int v : row) {
                out.print((v + 1) + " ");
            }
            out.println();
        }
    }

    /////////////////////////////////////////////////////////////////////

    private final static boolean MULTIPLE_TESTS = true;
    private final boolean ONLINE_JUDGE = !new File("input.txt").exists();
//    private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private final static int MAX_STACK_SIZE = 128;

    private final static boolean OPTIMIZE_READ_NUMBERS = false;

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private static long inverse(long x) {
        return binpow(x, MODULO - 2);
    }

    private static long binpow(long base, long power) {
        if (power == 0) return 1;
        if ((power & 1) == 0) {
            long half = binpow(base, power >> 1);
            return mult(half, half);
        } else {
            long prev = binpow(base, power - 1);
            return mult(prev, base);
        }
    }

    private static long add(long a, long b) { return (a + b) % MODULO; }

    @SuppressWarnings("unused")
    private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); }

    private static long mult(long a, long b) { return (a * b) % MODULO; }

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    boolean yesNo(boolean yes) {
        out.println(yes ? "YES" : "NO");
        return yes;
    }

    /////////////////////////////////////////////////////////////////////

    public void run(){
        try{
            timeInit();
            Locale.setDefault(Locale.US);

            init();

            if (ONLINE_JUDGE) {
                solve();
            } else {
                do {
                    try {
                        timeInit();
                        solve();
                        time();

                        out.println();
                        out.flush();
                    } catch (NumberFormatException | EOFException e) {
                        break;
                    }
                } while (MULTIPLE_TESTS);
            }

            out.close();
            time();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private BufferedReader in;
    private OutputWriter out;
    private StringTokenizer tok = new StringTokenizer("");

    public static void main(String[] args){
        new Thread(null, new B_Techno(), "", MAX_STACK_SIZE * (1L << 20)).start();
    }

    /////////////////////////////////////////////////////////////////////

    private void init() throws FileNotFoundException{
        Locale.setDefault(Locale.US);

        if (ONLINE_JUDGE){
            if (fileName.isEmpty()) {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new OutputWriter(System.out);
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new OutputWriter(fileName + ".out");
            }
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new OutputWriter("output.txt");
        }
    }

    ////////////////////////////////////////////////////////////////

    private long timeBegin;

    private void timeInit() {
        this.timeBegin = System.currentTimeMillis();
    }

    private void time(){
        long timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    @SuppressWarnings("unused")
    private void debug(Object... objects){
        if (ONLINE_JUDGE){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    /////////////////////////////////////////////////////////////////////

    private String delim = " ";

    private String readNullableLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private String readLine() {
        String line = readNullableLine();
        if (null == line) throw new EOFException();
        return line;
    }

    private String readString() {
        while(!tok.hasMoreTokens()){
            tok = new StringTokenizer(readLine(), delim);
        }

        return tok.nextToken(delim);
    }

    /////////////////////////////////////////////////////////////////

    private final char NOT_A_SYMBOL = '\0';

    @SuppressWarnings("unused")
    private char readChar() {
        try {
            int intValue = in.read();

            if (intValue == -1){
                return NOT_A_SYMBOL;
            }

            return (char) intValue;
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private char[] readCharArray() {
        return readLine().toCharArray();
    }

    @SuppressWarnings("unused")
    private char[][] readCharField(int rowsCount) {
        char[][] field = new char[rowsCount][];
        for (int row = 0; row < rowsCount; ++row) {
            field[row] = readCharArray();
        }

        return field;
    }

    /////////////////////////////////////////////////////////////////

    private long optimizedReadLong() {
        int sign = 1;
        long result = 0;
        boolean started = false;
        while (true) {
            try {
                int j = in.read();
                if (-1 == j) {
                    if (started) return sign * result;
                    throw new NumberFormatException();
                }

                if (j == '-') {
                    if (started) throw new NumberFormatException();
                    sign = -sign;
                }

                if ('0' <= j && j <= '9') {
                    result = result * 10 + j - '0';
                    started = true;
                } else if (started) {
                    return sign * result;
                }
            } catch (IOException e) {
                throw new RuntimeIOException(e);
            }
        }
    }

    private int readInt() {

        if (!OPTIMIZE_READ_NUMBERS) {
            return Integer.parseInt(readString());
        } else {
            return (int) optimizedReadLong();
        }
    }

    private int[] readIntArray(int size) {
        int[] array = new int[size];

        for (int index = 0; index < size; ++index){
            array[index] = readInt();
        }

        return array;
    }

    @SuppressWarnings("unused")
    private int[] readSortedIntArray(int size) {
        Integer[] array = new Integer[size];

        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    private int[] readIntArrayWithDecrease(int size) {
        int[] array = readIntArray(size);

        for (int i = 0; i < size; ++i) {
            array[i]--;
        }

        return array;
    }

    ///////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private int[][] readIntMatrix(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArray(columnsCount);
        }

        return matrix;
    }

    @SuppressWarnings("unused")
    private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
        }

        return matrix;
    }

    ///////////////////////////////////////////////////////////////////

    private long readLong() {
        if (!OPTIMIZE_READ_NUMBERS) {
            return Long.parseLong(readString());
        } else {
            return optimizedReadLong();
        }
    }

    @SuppressWarnings("unused")
    private long[] readLongArray(int size) {
        long[] array = new long[size];

        for (int index = 0; index < size; ++index){
            array[index] = readLong();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    private double readDouble() {
        return Double.parseDouble(readString());
    }

    @SuppressWarnings("unused")
    private double[] readDoubleArray(int size) {
        double[] array = new double[size];

        for (int index = 0; index < size; ++index){
            array[index] = readDouble();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private BigInteger readBigInteger() {
        return new BigInteger(readString());
    }

    @SuppressWarnings("unused")
    private BigDecimal readBigDecimal() {
        return new BigDecimal(readString());
    }

    /////////////////////////////////////////////////////////////////////

    private Point readPoint() {
        int x = readInt();
        int y = readInt();
        return new Point(x, y);
    }

    @SuppressWarnings("unused")
    private Point[] readPointArray(int size) {
        Point[] array = new Point[size];

        for (int index = 0; index < size; ++index){
            array[index] = readPoint();
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    @Deprecated
    @SuppressWarnings("unused")
    private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
        @SuppressWarnings("unchecked")
        List<Integer>[] graph = new List[vertexNumber];

        for (int index = 0; index < vertexNumber; ++index){
            graph[index] = new ArrayList<>();
        }

        while (edgeNumber-- > 0){
            int from = readInt() - 1;
            int to = readInt() - 1;

            graph[from].add(to);
            graph[to].add(from);
        }

        return graph;
    }

    private static class GraphBuilder {

        final int size;
        final List<Integer>[] edges;

        static GraphBuilder createInstance(int size) {
            @SuppressWarnings("unchecked")
            List<Integer>[] edges = new List[size];
            for (int v = 0; v < size; ++v) {
                edges[v] = new ArrayList<>();
            }

            return new GraphBuilder(edges);
        }

        private GraphBuilder(List<Integer>[] edges) {
            this.size = edges.length;
            this.edges = edges;
        }

        public void addEdge(int from, int to) {
            addDirectedEdge(from, to);
            addDirectedEdge(to, from);
        }

        public void addDirectedEdge(int from, int to) {
            edges[from].add(to);
        }

        public int[][] build() {
            int[][] graph = new int[size][];
            for (int v = 0; v < size; ++v) {
                List<Integer> vEdges = edges[v];
                graph[v] = castInt(vEdges);
            }

            return graph;
        }
    }

    @SuppressWarnings("unused")
    private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1;

    @SuppressWarnings("unused")
    private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) {
        return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false);
    }

    private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber,
                                        int indexation, boolean directed
    ) {
        GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber);
        for (int i = 0; i < edgesNumber; ++i) {
            int from = readInt() - indexation;
            int to = readInt() - indexation;

            if (directed) graphBuilder.addDirectedEdge(from, to);
            else graphBuilder.addEdge(from, to);
        }

        return graphBuilder.build();
    }

    private static class Edge {
        int to;
        int w;

        Edge(int to, int w) {
            this.to = to;
            this.w = w;
        }
    }

    @SuppressWarnings("unused")
    private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) {
        return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false);
    }

    private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber,
                                       int indexation, boolean directed) {
        @SuppressWarnings("unchecked")
        List<Edge>[] graph = new List[vertexNumber];
        for (int v = 0; v < vertexNumber; ++v) {
            graph[v] = new ArrayList<>();
        }

        while (edgesNumber --> 0) {
            int from = readInt() - indexation;
            int to = readInt() - indexation;
            int w = readInt();

            graph[from].add(new Edge(to, w));
            if (!directed) graph[to].add(new Edge(from, w));
        }

        Edge[][] graphArrays = new Edge[vertexNumber][];
        for (int v = 0; v < vertexNumber; ++v) {
            graphArrays[v] = graph[v].toArray(new Edge[0]);
        }

        return graphArrays;
    }

    /////////////////////////////////////////////////////////////////////

    private static class IntIndexPair {

        @SuppressWarnings("unused")
        static Comparator<IntIndexPair> increaseComparator = (indexPair1, indexPair2) -> {
            int value1 = indexPair1.value;
            int value2 = indexPair2.value;

            if (value1 != value2) {
                return value1 - value2;
            }

            int index1 = indexPair1.index;
            int index2 = indexPair2.index;

            return index1 - index2;
        };

        @SuppressWarnings("unused")
        static Comparator<IntIndexPair> decreaseComparator = (indexPair1, indexPair2) -> {
            int value1 = indexPair1.value;
            int value2 = indexPair2.value;

            if (value1 != value2) {
                return -(value1 - value2);
            }

            int index1 = indexPair1.index;
            int index2 = indexPair2.index;

            return index1 - index2;
        };

        @SuppressWarnings("unused")
        static IntIndexPair[] from(int[] array) {
            IntIndexPair[] iip = new IntIndexPair[array.length];
            for (int i = 0; i < array.length; ++i) {
                iip[i] = new IntIndexPair(array[i], i);
            }

            return iip;
        }

        int value, index;

        IntIndexPair(int value, int index) {
            super();
            this.value = value;
            this.index = index;
        }

        @SuppressWarnings("unused")
        int getRealIndex() {
            return index + 1;
        }
    }

    @SuppressWarnings("unused")
    private IntIndexPair[] readIntIndexArray(int size) {
        IntIndexPair[] array = new IntIndexPair[size];

        for (int index = 0; index < size; ++index) {
            array[index] = new IntIndexPair(readInt(), index);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    private static class OutputWriter extends PrintWriter {

        final int DEFAULT_PRECISION = 12;

        private int precision;
        private String format, formatWithSpace;

        {
            precision = DEFAULT_PRECISION;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        OutputWriter(OutputStream out) {
            super(out);
        }

        OutputWriter(String fileName) throws FileNotFoundException {
            super(fileName);
        }

        int getPrecision() {
            return precision;
        }

        void setPrecision(int precision) {
            precision = max(0, precision);
            this.precision = precision;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        String createFormat(int precision){
            return "%." + precision + "f";
        }

        @Override
        public void print(double d){
            printf(format, d);
        }

        @Override
        public void println(double d){
            print(d);
            println();
        }

        void printWithSpace(double d){
            printf(formatWithSpace, d);
        }

        void printAll(double...d){
            for (int i = 0; i < d.length - 1; ++i){
                printWithSpace(d[i]);
            }

            print(d[d.length - 1]);
        }

        @SuppressWarnings("unused")
        void printlnAll(double... d){
            printAll(d);
            println();
        }

        void printAll(int... array) {
        	for (int value : array) {
        		print(value + " ");
        	}
        }

        @SuppressWarnings("unused")
        void printlnAll(int... array) {
        	printAll(array);
        	println();
        }

        void printAll(long... array) {
        	for (long value : array) {
        		print(value + " ");
        	}
        }

        @SuppressWarnings("unused")
        void printlnAll(long... array) {
        	printAll(array);
        	println();
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class EOFException extends RuntimeException {

        EOFException() {
            super();
        }
    }

    private static class RuntimeIOException extends RuntimeException {

        /**
         *
         */
        private static final long serialVersionUID = -6463830523020118289L;

        RuntimeIOException(Throwable cause) {
            super(cause);
        }
    }

    /////////////////////////////////////////////////////////////////////
    //////////////// Some useful constants andTo functions ////////////////
    /////////////////////////////////////////////////////////////////////

    private static void swap(int[] array, int i, int j) {
        if (i != j) {
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
    }

    private static <T> void swap(T[] array, int i, int j) {
        if (i != j) {
            T tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
    }

    private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private static final int[][] steps8 = {
            {-1, 0}, {1, 0}, {0, -1}, {0, 1},
            {-1, -1}, {1, 1}, {1, -1}, {-1, 1}
    };

    @SuppressWarnings("unused")
    private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
        return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
    }

    private static boolean checkIndex(int index, int lim){
        return (0 <= index && index < lim);
    }

    /////////////////////////////////////////////////////////////////////

    private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); }

    @SuppressWarnings("unused")
    private static boolean checkBit(long mask, int bit){
        return getBit(mask, bit) != 0;
    }

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private static long getSum(int[] array) {
        long sum = 0;
        for (int value: array) {
            sum += value;
        }

        return sum;
    }

    @SuppressWarnings("unused")
    private static Point getMinMax(int[] array) {
        int min = array[0];
        int max = array[0];

        for (int index = 0, size = array.length; index < size; ++index, ++index) {
            int value = array[index];

            if (index == size - 1) {
                min = min(min, value);
                max = max(max, value);
            } else {
                int otherValue = array[index + 1];

                if (value <= otherValue) {
                    min = min(min, value);
                    max = max(max, otherValue);
                } else {
                    min = min(min, otherValue);
                    max = max(max, value);
                }
            }
        }

        return new Point(min, max);
    }

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private static boolean isPrime(int x) {
        if (x < 2) return false;
        for (int d = 2; d * d <= x; ++d) {
            if (x % d == 0) return false;
        }

        return true;
    }

    @SuppressWarnings("unused")
    private static int[] getPrimes(int n) {
        boolean[] used = new boolean[n];
        used[0] = used[1] = true;

        int size = 0;
        for (int i = 2; i < n; ++i) {
            if (!used[i]) {
                ++size;
                for (int j = 2 * i; j < n; j += i) {
                    used[j] = true;
                }
            }
        }

        int[] primes = new int[size];
        for (int i = 0, cur = 0; i < n; ++i) {
            if (!used[i]) {
                primes[cur++] = i;
            }
        }

        return primes;
    }

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    int[] getDivisors(int value) {
        List<Integer> divisors = new ArrayList<>();
        for (int divisor = 1; divisor * divisor <= value; ++divisor) {
            if (value % divisor == 0) {
                divisors.add(divisor);
                if (divisor * divisor != value) {
                    divisors.add(value / divisor);
                }
            }
        }

        return castInt(divisors);
    }

    @SuppressWarnings("unused")
    long[] getDivisors(long value) {
        List<Long> divisors = new ArrayList<>();
        for (long divisor = 1; divisor * divisor <= value; ++divisor) {
            if (value % divisor == 0) {
                divisors.add(divisor);
                if (divisor * divisor != value) {
                    divisors.add(value / divisor);
                }
            }
        }

        return castLong(divisors);
    }

    /////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unused")
    private static long lcm(long a, long b) {
        return a / gcd(a, b) * b;
    }

    private static long gcd(long a, long b) {
        return (a == 0 ? b : gcd(b % a, a));
    }

    /////////////////////////////////////////////////////////////////////

    private static int[] castInt(List<Integer> list) {
        int[] array = new int[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    @SuppressWarnings("unused")
    private static long[] castLong(List<Long> list) {
        long[] array = new long[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    /**
     * Generates list with keys 0..<bowlsCount
     * @param n - exclusive limit of sequence
     */
    @SuppressWarnings("unused")
    private static List<Integer> order(int n) {
        List<Integer> sequence = new ArrayList<>();
        for (int i = 0; i < n; ++i) {
            sequence.add(i);
        }

        return sequence;
    }

    @SuppressWarnings("unused")
    private static List<Integer> shuffled(List<Integer> list) {
        Collections.shuffle(list, rnd);
        return list;
    }
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r, k;
    cin>>t;
    vector<vector<int>> a(1e6);
    vector<vector<int>> ans(2000);
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                if(j == 0) k = r;
                b.push_back(r);
            }
            a[k] = b;
            b.clear();
        }
        int k1 = 0;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                if(!a[r].empty()){
                    ans[k1] = a[r];
                    k1++;
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r, k;
    cin>>t;
    vector<vector<int>> a(1e8);
    vector<vector<int>> ans(2000);
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                if(j == 0) k = r;
                b.push_back(r);
            }
            a[k] = b;
            b.clear();
        }
        int k1 = 0;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                if(!a[r].empty()){
                    ans[k1] = a[r];
                    k1++;
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r, k;
    cin>>t;
    vector<vector<int>> a(2000);
    vector<vector<int>> ans(2000);
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                if(j == 0) k = r;
                b.push_back(r);
            }
            a[k] = b;
            b.clear();
        }
        int k1 = 0;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                if(!a[r].empty()){
                    ans[k1] = a[r];
                    k1++;
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r, k;
    cin>>t;
    vector<vector<int>> a(1e7);
    vector<vector<int>> ans(2000);
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                if(j == 0) k = r;
                b.push_back(r);
            }
            a[k] = b;
            b.clear();
        }
        int k1 = 0;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                if(!a[r].empty()){
                    ans[k1] = a[r];
                    k1++;
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r, k;
    cin>>t;
    vector<vector<int>> a(1e9);
    vector<vector<int>> ans(2000);
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                if(j == 0) k = r;
                b.push_back(r);
            }
            a[k] = b;
            b.clear();
        }
        int k1 = 0;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                if(!a[r].empty()){
                    ans[k1] = a[r];
                    k1++;
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define pii pair<int,int>
#define ll long long

struct P{
    int x, y;
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, t, m, r;
    cin>>t;
    vector<vector<int>> a;
    vector<vector<int>> ans;
    vector<int> b;
    for(int i = 0;i<t;i++){
        cin>>n>>m;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cin>>r;
                b.push_back(r);
            }
            a.push_back(b);
            b.clear();
        }
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                cin>>r;
                for(int i = 0;i<n;i++){
                    if(a[i][0] == r)
                        ans.push_back(a[i]);
                }
            }
        }
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<"\n";
        }
        a.clear();
        ans.clear();
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

void solve()
{

int n,m;
cin >> n >> m;

if (n==1)
{
    vector <int> now(m);
    for (int i=0; i<m; i++) cin >> now[i];
    int x; for (int i=0; i<m; i++) cin >> x;
    for (int i=0; i<m; i++) cout << now[i] << " "; cout << "\n"; return;
}

if (m==1)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cout << now[i] << "\n"; return;
}

vector <int> rs(n); // rs[i]=j
vector<vector <int>> a;
for (int i=0; i<n; i++)
{
    vector <int> now(m);
        for (int i=0; i<m; i++)
            cin >> now[i];
    a.push_back(now);
}

vector <pair<int,int>> first;
for (int i=0; i<n; i++) first.push_back({a[i][0],i});
sort(first.begin(),first.end());

for (int i=0; i<m; i++)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    vector<int> x = now;
    sort(x.begin(),x.end());

    bool is = true;
    for (int i=0; i<n; i++) if (first[i].first!=now[i]){is = false; break;}
    if (!is) continue;

    for (int i=0; i<n; i++)
    {
        rs[first[i].second]=i;
    }

    //     first[j] =  now[i]  -> rs[j] = i
}

for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << a[rs[i]][j] << " ";
            cout << "\n";
    }

}

int main()
{

int t=1;
cin >> t;
while (t--) solve();

}


#include<bits/stdc++.h>
using namespace std;

void solve()
{

int n,m;
cin >> n >> m;

if (n==1)
{
    vector <int> now(m);
    for (int i=0; i<m; i++) cin >> now[i];
    int x; for (int i=0; i<m; i++) cin >> x;
    for (int i=0; i<m; i++) cout << now[i] << " "; cout << "\n"; return;
}

if (m==1)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cout << now[i] << "\n"; return;
}

vector <int> rs(n); // rs[i]=j
vector<vector <int>> a;
for (int i=0; i<n; i++)
{
    vector <int> now(m);
        for (int i=0; i<m; i++)
            cin >> now[i];
    a.push_back(now);
}

vector <int> first;
for (int i=0; i<n; i++) first.push_back(a[i][0]);

map<int,int> mp;
for (int i=0; i<n; i++) mp[a[i][0]]=i;

sort(first.begin(),first.end());

/*
for (int i=0; i<n; i++)
    cout << first[i].first << " " << first[i].second << "\n";
*/

for (int i=0; i<m; i++)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    vector<int> x = now;
    sort(x.begin(),x.end());

    /*
    for (int i=0; i<n; i++)
        cout << first[i].first << " " << x[i] << "\n";
*/
    bool is = true;
    for (int i=0; i<n; i++) if (first[i]!=x[i]){is = false; break;}
    if (!is) continue;

//    for (int y:x) cout << y << " "; cout << "\n";

    for (int i=0; i<n; i++)
    {
        rs[i]=mp[now[i]];
    }

    //     first[j] =  now[i]  -> rs[j] = i
}

//for (int i=0; i<n; i++) cout << rs[i] << "\n"[i!=n-1];

for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << a[rs[i]][j] << " ";
            cout << "\n";
    }

}

int main()
{

int t=1;
cin >> t;
while (t--) solve();

}

/*
1
4 2
1 6
3 2
8 4
7 5
5 6 2 4
7 1 3 8
*/


#include<bits/stdc++.h>
using namespace std;

void solve()
{

int n,m;
cin >> n >> m;

if (n==1)
{
    vector <int> now(m);
    for (int i=0; i<m; i++) cin >> now[i];
    int x; for (int i=0; i<m; i++) cin >> x;
    for (int i=0; i<m; i++) cout << now[i] << " "; cout << "\n"; return;
}

if (m==1)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cout << now[i] << "\n"; return;
}

vector <int> rs(n); // rs[i]=j
vector<vector <int>> a;
for (int i=0; i<n; i++)
{
    vector <int> now(m);
        for (int i=0; i<m; i++)
            cin >> now[i];
    a.push_back(now);
}

vector <pair<int,int>> first;
for (int i=0; i<n; i++) first.push_back({a[i][0],i});
sort(first.begin(),first.end());

/*
for (int i=0; i<n; i++)
    cout << first[i].first << " " << first[i].second << "\n";
*/

map<int,int> mp;
for (auto x:first) mp[x.first]=x.second;

for (int i=0; i<m; i++)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    vector<int> x = now;
    sort(x.begin(),x.end());

    /*
    for (int i=0; i<n; i++)
        cout << first[i].first << " " << x[i] << "\n";
*/
    bool is = true;
    for (int i=0; i<n; i++) if (first[i].first!=x[i]){is = false; break;}
    if (!is) continue;

//    for (int y:x) cout << y << " "; cout << "\n";

    for (int i=0; i<n; i++)
    {
        rs[mp[now[i]]]=i;
    }

    //     first[j] =  now[i]  -> rs[j] = i
}

//for (int i=0; i<n; i++) cout << rs[i] << "\n"[i!=n-1];

for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << a[rs[i]][j] << " ";
            cout << "\n";
    }

}

int main()
{

int t=1;
cin >> t;
while (t--) solve();

}

/*
1
4 2
4 8
1 3
2 7
6 5
1 4 2 6
3 8 7 5
*/


#include<bits/stdc++.h>
using namespace std;

void solve()
{

int n,m;
cin >> n >> m;

if (n==1)
{
    vector <int> now(m);
    for (int i=0; i<m; i++) cin >> now[i];
    int x; for (int i=0; i<m; i++) cin >> x;
    for (int i=0; i<m; i++) cout << now[i] << " "; cout << "\n"; return;
}

if (m==1)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cout << now[i] << " "; cout << "\n"; return;
}

vector <int> rs(n); // rs[i]=j
vector<vector <int>> a;
for (int i=0; i<n; i++)
{
    vector <int> now(m);
        for (int i=0; i<m; i++)
            cin >> now[i];
    a.push_back(now);
}

vector <pair<int,int>> first;
for (int i=0; i<n; i++) first.push_back({a[i][0],i});
sort(first.begin(),first.end());

for (int i=0; i<m; i++)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    vector<int> x = now;
    sort(x.begin(),x.end());

    bool is = true;
    for (int i=0; i<n; i++) if (first[i].first!=now[i]){is = false; break;}
    if (!is) continue;

    for (int i=0; i<n; i++)
    {
        rs[first[i].second]=i;
    }

    //     first[j] =  now[i]  -> rs[j] = i
}

for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << a[rs[i]][j] << " ";
            cout << "\n";
    }

}

int main()
{

int t=1;
cin >> t;
while (t--) solve();

}


#include<bits/stdc++.h>
using namespace std;

void solve()
{

int n,m;
cin >> n >> m;

if (n==1)
{
    vector <int> now(m);
    for (int i=0; i<m; i++) cin >> now[i];
    int x; for (int i=0; i<m; i++) cin >> x;
    for (int i=0; i<m; i++) cout << now[i] << " "; cout << "\n"; return;
}

if (m==1)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cin >> now[i];
    for (int i=0; i<n; i++) cout << now[i] << "\n"; return;
}

vector <int> rs(n); // rs[i]=j
vector<vector <int>> a;
for (int i=0; i<n; i++)
{
    vector <int> now(m);
        for (int i=0; i<m; i++)
            cin >> now[i];
    a.push_back(now);
}

vector <pair<int,int>> first;
for (int i=0; i<n; i++) first.push_back({a[i][0],i});
sort(first.begin(),first.end());

for (int i=0; i<n; i++)
    cout << first[i].first << " " << first[i].second << "\n";

map<int,int> mp;
for (auto x:first) mp[x.first]=x.second;

for (int i=0; i<m; i++)
{
    vector <int> now(n);
    for (int i=0; i<n; i++) cin >> now[i];
    vector<int> x = now;
    sort(x.begin(),x.end());

    /*
    for (int i=0; i<n; i++)
        cout << first[i].first << " " << x[i] << "\n";
*/
    bool is = true;
    for (int i=0; i<n; i++) if (first[i].first!=x[i]){is = false; break;}
    if (!is) continue;

//    for (int y:x) cout << y << " "; cout << "\n";

    for (int i=0; i<n; i++)
    {
        rs[mp[now[i]]]=i;
    }

    //     first[j] =  now[i]  -> rs[j] = i
}

//for (int i=0; i<n; i++) cout << rs[i] << "\n"[i!=n-1];

for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
            cout << a[rs[i]][j] << " ";
            cout << "\n";
    }

}

int main()
{

int t=1;
cin >> t;
while (t--) solve();

}

/*
1
4 2
4 8
1 3
2 7
6 5
1 4 2 6
3 8 7 5
*/


#include <bits/stdc++.h>
#define ll long long
#define f first
#define s second
using namespace std;

int main()
{
    int q;
    cin >> q;
    while(q--)
    {
        int n, m;
        cin >> n >> m;
        vector <int> zh[n];
        map<int, int> hz;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                {
                    int a;
                    cin >> a;
                    zh[i].push_back(a);
                }
        vector <int> s;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int a;
                cin >> a;
                if(i == 0)
                {
                    hz[a] = j;
                }
                if(j == 0)
                    s.push_back(a);
            }
        }
        int ind = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
            {
                if(zh[0][j] == s[i])
                {
                    ind = i;
                    break;
                }
            }

        pair <int, vector<int>> ans[n];
        for (int i = 0; i < n; i++)
        {
            ans[i] = {hz[zh[i][ind]], zh[i]};
        }
        sort(ans, ans + n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
                cout << ans[i].s[j] << " ";
            cout << endl;
        }
    }
}


#include <bits/stdc++.h>
#define ll long long
#define f first
#define s second
using namespace std;

int main()
{
    int q;
    cin >> q;
    while(q--)
    {
        int n, m;
        cin >> n >> m;
        vector <int> zh[n];
        map<int, int> hz;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                {
                    int a;
                    cin >> a;
                    zh[i].push_back(a);
                }
        int s[m][n];
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int a;
                cin >> a;
                if(i == 0)
                {
                    hz[a] = j;
                }
            }
        }
        pair <int, vector<int>> ans[n];
        for (int i = 0; i < n; i++)
        {
            ans[i] = {hz[zh[i][0]], zh[i]};
        }
        sort(ans, ans + n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
                cout << ans[i].s[j] << " ";
            cout << endl;
        }
    }
}


#include <bits/stdc++.h>
#define ll long long
#define f first
#define s second
using namespace std;

int main()
{
    int q;
    cin >> q;
    while(q--)
    {
        int n, m;
        cin >> n >> m;
        vector <int> zh[n];
        map<int, int> hz;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                {
                    int a;
                    cin >> a;
                    zh[i].push_back(a);
                }
        vector <int> s;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int a;
                cin >> a;
                hz[a] = j;
            }
        }
        int ind = 0;
        pair <int, vector<int>> ans[n];
        for (int i = 0; i < n; i++)
        {
            ans[i] = {hz[zh[i][0]], zh[i]};
        }
        sort(ans, ans + n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
                cout << ans[i].s[j] << " ";
            cout << endl;
        }
    }
}


#include <bits/stdc++.h>
#define ll long long
#define f first
#define s second
using namespace std;

int main()
{
    int q;
    cin >> q;
    while(q--)
    {
        int n, m;
        cin >> n >> m;
        vector <int> zh[n];
        map<int, int> hz;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                {
                    int a;
                    cin >> a;
                    zh[i].push_back(a);
                }
        vector <int> s;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int a;
                cin >> a;
                if(i == 0)
                {
                    hz[a] = j;
                }
                if(j == 0)
                    s.push_back(a);
            }
        }
        int ind = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
            {
                if(zh[0][j] == s[i])
                {
                    ind = j;
                    break;
                }
            }

        pair <int, vector<int>> ans[n];
        for (int i = 0; i < n; i++)
        {
            ans[i] = {hz[zh[i][ind]], zh[i]};
        }
        sort(ans, ans + n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
                cout << ans[i].s[j] << " ";
            cout << endl;
        }
    }
}


#include <bits/stdc++.h>
#define pb push_back
#define int long long
#define R(i, n) for (int i = 0; i < (n); i++)
#define RE(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define vi vector<int>
#define vb vector<bool>
#define ld long double
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()

using namespace std;

template <typename T> ostream& operator << (ostream& out, vector <T>& p) {
    for (auto& el : p) out << el << ' ';
    return out;
}
template <typename T> istream& operator >> (istream& inp, vector <T>& p) {
    for (auto& el : p) inp >> el;
    return inp;
}

const int N = 10;
const int INF = 1e15;
extern const int MOD = 1e9+7;

void solve() {
    int n,m;
    cin>>n>>m;
    vector<vi> str(n, vi(m)), str1(n, vi(m)), stb(n, vi(m));
    vector<vi> g(n, vi(m));
    R(i, n){
        cin>>str[i];
        str1[i] = str[i];
        sort(all(str[i]));
    }
    R(i, m){
        R(j, n){
            cin>>stb[j][i];
        }
    }
    R(i, n){
        sort(all(stb[i]));
    }

    R(i, n){
        int k = -1;
        R(t, n){
            if(str[i] == stb[t]) k = t;
        }
        g[k] = str1[i];
    }
    R(i, n)
        cout<<g[i]<<endl;
}

signed main() {
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q = 1;
    cin>>q;
    R(i, q)
        solve();
    return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define int long long
#define R(i, n) for (int i = 0; i < (n); i++)
#define RE(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define vi vector<int>
#define vb vector<bool>
#define ld long double
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()

using namespace std;

template <typename T> ostream& operator << (ostream& out, vector <T>& p) {
    for (auto& el : p) out << el << ' ';
    return out;
}
template <typename T> istream& operator >> (istream& inp, vector <T>& p) {
    for (auto& el : p) inp >> el;
    return inp;
}

const int N = 10;
const int INF = 1e15;
extern const int MOD = 1e9+7;

void solve() {
    int n,m;
    cin>>n>>m;
    vector<vi> str(n, vi(m)), stb(m, vi(n));
    vector<vi> g(n, vi(m));
    R(i, n){
        cin>>str[i];
    }
    R(i, m){
        cin>>stb[i];
    }

    R(i, n){
        int k = -1;
        R(t, n){
            vi a,b;
            R(j, m){
                a.pb(stb[j][t]);
                b.pb(str[i][j]);
            }
            sort(all(a));
            sort(all(b));
            if(a == b) k = t;
        }
        g[k] = str[i];
    }
    R(i, n)
        cout<<g[i]<<endl;
}

signed main() {
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q = 1;
    cin>>q;
    R(i, q)
        solve();
    return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define int long long
#define R(i, n) for (int i = 0; i < (n); i++)
#define RE(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define vi vector<int>
#define vb vector<bool>
#define ld long double
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()

using namespace std;

template <typename T> ostream& operator << (ostream& out, vector <T>& p) {
    for (auto& el : p) out << el << ' ';
    return out;
}
template <typename T> istream& operator >> (istream& inp, vector <T>& p) {
    for (auto& el : p) inp >> el;
    return inp;
}

const int N = 10;
const int INF = 1e15;
extern const int MOD = 1e9+7;

void solve() {
    int n,m;
    cin>>n>>m;
    vector<vi> str(n, vi(m)), stb(m, vi(n));
    vector<vi> g(n, vi(m));
    R(i, n){
        cin>>str[i];
    }
    R(i, m){
        cin>>stb[i];
    }

    R(i, n){
        int k = 0;
        R(t, n){
            bool f = true;
            R(j, m){
                if(stb[j][t] != str[i][j]) f = false;
            }
            if(f) k = t;
        }
        g[k] = str[i];
    }
    R(i, n)
        cout<<g[i]<<endl;
}

signed main() {
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q = 1;
    cin>>q;
    R(i, q)
        solve();
    return 0;
}


#include <bits/stdc++.h>
#define _USE_MATH_DEFINES

#include <cmath>
#define pb push_back
#define int long long
#define R(i, n) for (int i = 0; i < (n); i++)
#define RE(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define vi vector<int>
#define vb vector<bool>
#define ld long double
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()

using namespace std;

template <typename T> ostream& operator << (ostream& out, vector <T>& p) {
    for (auto& el : p) out << el << ' ';
    return out;
}
template <typename T> istream& operator >> (istream& inp, vector <T>& p) {
    for (auto& el : p) inp >> el;
    return inp;
}

const int N = 10;
const int INF = 1e15;
extern const int MOD = 1e9+7;

void solve() {
    int n,m;
    cin>>n>>m;
    vector<vi> str(n), stb(m);
    vector<vi> g(n, vi(m));
    R(i, n){
        vi a(m);
        cin>>a;
        str[i] = a;
    }
    R(i, m){
        vi a(n);
        cin>>a;
        stb[i] = a;
    }

    R(i, n){
        int k = -1;
        R(t, n){
            bool f = true;
            R(j, m){
                if(stb[j][t] != str[i][j]) f = false;
            }
            if(f) k = t;
        }
        g[k] = str[i];
    }
    R(i, n){
        cout<<g[i]<<endl;
    }
}

signed main() {
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int q = 1;
    cin>>q;
    R(i, q)
        solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ar(a,i,j) a[i][j]
#define arr(a,i,j,k) a[i][j][k]
#define FastIO ios::sync_with_stdio(false); cin.tie(nullptr);cout.tie(nullptr)
#define IN freopen("E:\\programming\\New folder\\input.txt","r+",stdin)
#define OUT freopen("E:\\programming\\New folder\\output.txt","w+",stdout)
#define inf 1e18
#define eps 1e-15
#define ll long long
#define nl printf("\n")
#define gap printf(" ")
#define in1(a) scanf("%I64d",&a)
#define in2(a,b) scanf("%I64d %I64d",&a,&b)
#define in3(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c)
#define ins(s) scanf("%s",&s)
#define out1(a) printf("%I64d",a)
#define out2(a,b) printf("%I64d %I64d",a,b)
#define out3(a,b,c) printf("%I64d %I64d %I64d",a,b,c)
#define outs(s) printf("%s",s)
#define ilup(i,a,n) for(ll i=a;i<=n;i++)
#define dlup(i,n,a) for(ll i=n;i>=a;i--)
#define setarray(arr,a,n,val) for(ll i = a; i <= n; i++)arr[i] = val;

void check(vector<ll>&a)
{
    ilup(i,0,a.size() -1 )
    {
        out1(a[i]);
        gap;
    }
    nl;
}

void check(ll a[],ll n)
{
    ilup(i,0,n-1)
    {
        out1(a[i]);
        gap;
    }
    nl;
}

#define MAX 505
ll t,n,m,rows[MAX][MAX],cols[MAX][MAX],k;
map<ll,int> mp;

int main()
{
    // FastIO;
    #ifndef
    IN;OUT;
    #endif

    in1(t);
    while(t--)
    {
        in2(n,m);
        k = -1;
        ilup(i,1,n)
        {
            ilup(j, 1, m)
            {
                in1(rows[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j, 1, n)
            {
                in1(cols[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j,1,n)
            {
                if(cols[i][1] == rows[j][1])
                {
                    k = i;
                    break;
                }
            }
            if(k != -1)
            {
                break;
            }
        }
        // out1(k);nl;
        ilup(i,1,n)
        {
            mp[rows[i][1]] = i;
        }
        ilup(i,1,n)
        {
            ilup(j,1,m)
            {
                out1(rows[mp[cols[k][i]]][j]);gap;
            }
            nl;
        }
    }
}


import sys

// sys.stdin = open("E:\\programming\\New folder\\input.txt", "r")
// sys.stdout = open("E:\\programming\\New folder\\output.txt", "w")

t = int(input())

for tc in range(t):
    n, m = map(int, input().split())
    rows = []
    cols = []
    ans = []
    k = -1
    for i in range(n):
        rows.append(list(map(int, input().split())))
    for i in range(m):
        cols.append(list(map(int, input().split())))
    for i in range(m):
        for j in range(n):
            if cols[i][0] == rows[j][0]:
                k = i
                ans.append(rows[j])
                break
        if k != -1:
            break
    d = dict()
    c = 0
    for row in rows:
        d[row[0]] = c
        c += 1
    # print(d)
    # print(k)
    for i in range(1, n):
        ans.append(rows[d[cols[k][i]]])
    for i in ans:
        print(*i)


#include<bits/stdc++.h>
using namespace std;

#define ar(a,i,j) a[i][j]
#define arr(a,i,j,k) a[i][j][k]
#define FastIO ios::sync_with_stdio(false); cin.tie(nullptr);cout.tie(nullptr)
#define IN freopen("E:\\programming\\New folder\\input.txt","r+",stdin)
#define OUT freopen("E:\\programming\\New folder\\output.txt","w+",stdout)
#define inf 1e18
#define eps 1e-15
#define ll long long
#define nl printf("\n")
#define gap printf(" ")
#define in1(a) scanf("%I64d",&a)
#define in2(a,b) scanf("%I64d %I64d",&a,&b)
#define in3(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c)
#define ins(s) scanf("%s",&s)
#define out1(a) printf("%I64d",a)
#define out2(a,b) printf("%I64d %I64d",a,b)
#define out3(a,b,c) printf("%I64d %I64d %I64d",a,b,c)
#define outs(s) printf("%s",s)
#define ilup(i,a,n) for(ll i=a;i<=n;i++)
#define dlup(i,n,a) for(ll i=n;i>=a;i--)
#define setarray(arr,a,n,val) for(ll i = a; i <= n; i++)arr[i] = val;

void check(vector<ll>&a)
{
    ilup(i,0,a.size() -1 )
    {
        out1(a[i]);
        gap;
    }
    nl;
}

void check(ll a[],ll n)
{
    ilup(i,0,n-1)
    {
        out1(a[i]);
        gap;
    }
    nl;
}

#define MAX 505
ll t,n,m,rows[MAX][MAX],cols[MAX][MAX],k;
map<ll,int> mp;

int main()
{
    // FastIO;
    // IN;OUT;
    in1(t);
    while(t--)
    {
        in2(n,m);
        k = -1;
        ilup(i,1,n)
        {
            ilup(j, 1, m)
            {
                in1(rows[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j, 1, n)
            {
                in1(cols[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j,1,n)
            {
                if(cols[i][1] == rows[j][1])
                {
                    k = i;
                    break;
                }
            }
            if(k != -1)
            {
                break;
            }
        }
        // out1(k);nl;
        ilup(i,1,n)
        {
            mp[rows[i][1]] = i;
        }
        ilup(i,1,n)
        {
            ilup(j,1,m)
            {
                out1(rows[mp[cols[k][i]]][j]);gap;
            }
            nl;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;

#define ar(a,i,j) a[i][j]
#define arr(a,i,j,k) a[i][j][k]
#define FastIO ios::sync_with_stdio(false); cin.tie(nullptr);cout.tie(nullptr)
#define IN freopen("E:\\programming\\New folder\\input.txt","r+",stdin)
#define OUT freopen("E:\\programming\\New folder\\output.txt","w+",stdout)
#define inf 1e18
#define eps 1e-15
#define ll long long
#define nl printf("\n")
#define gap printf(" ")
#define in1(a) scanf("%I64d",&a)
#define in2(a,b) scanf("%I64d %I64d",&a,&b)
#define in3(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c)
#define ins(s) scanf("%s",&s)
#define out1(a) printf("%I64d",a)
#define out2(a,b) printf("%I64d %I64d",a,b)
#define out3(a,b,c) printf("%I64d %I64d %I64d",a,b,c)
#define outs(s) printf("%s",s)
#define ilup(i,a,n) for(ll i=a;i<=n;i++)
#define dlup(i,n,a) for(ll i=n;i>=a;i--)
#define setarray(arr,a,n,val) for(ll i = a; i <= n; i++)arr[i] = val;

void check(vector<ll>&a)
{
    ilup(i,0,a.size() -1 )
    {
        out1(a[i]);
        gap;
    }
    nl;
}

void check(ll a[],ll n)
{
    ilup(i,0,n-1)
    {
        out1(a[i]);
        gap;
    }
    nl;
}

#define MAX 505
ll t,n,m,rows[MAX][MAX],cols[MAX][MAX],k;
map<ll,int> mp;

int main()
{
    // FastIO;
    #ifndef ONLINE_JUDGE
    IN;OUT;
    #endif

    in1(t);
    while(t--)
    {
        in2(n,m);
        k = -1;
        ilup(i,1,n)
        {
            ilup(j, 1, m)
            {
                in1(rows[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j, 1, n)
            {
                in1(cols[i][j]);
            }
        }
        ilup(i,1,m)
        {
            ilup(j,1,n)
            {
                if(cols[i][1] == rows[j][1])
                {
                    k = i;
                    break;
                }
            }
            if(k != -1)
            {
                break;
            }
        }
        // out1(k);nl;
        ilup(i,1,n)
        {
            mp[rows[i][1]] = i;
        }
        ilup(i,1,n)
        {
            ilup(j,1,m)
            {
                out1(rows[mp[cols[k][i]]][j]);gap;
            }
            nl;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323846
#define E  2.71828182845904523536
#define pout(x) cout << fixed << setprecision(x)
#define INF INFINITY
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define siz(x) (ll)x.size()
#define all(x) x.begin(), x.end()
typedef long double ld;
typedef long long ll;
ll _, n, m, k, s, x, y, p;
ll a[1001][1001];
ll st[1001][1001];
ll fin[1001][1001];
void solve();
int main() {
    cin >> _;
    while(_--) solve();
}
void solve() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> a[i][j];
            fin[i][j] = 0;
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> st[j][i];
        }
    }
    for(int i = 0; i < m; i++){
        for(int k = 0; k < m; k++){
            set<ll> sttt;
            for(int j = 0; j < n; j++){
                sttt.insert(a[j][i]);
                sttt.insert(st[j][k]);
            }
            if(siz(sttt) == n){
                for(int j = 0; j < n; j++){
                    fin[j][k] = st[j][k];
                }
            }
        }
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cout << fin[i][j] << " ";
        }
        cout << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323846
#define E  2.71828182845904523536
#define pout(x) cout << fixed << setprecision(x)
#define INF INFINITY
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define siz(x) (ll)x.size()
#define all(x) x.begin(), x.end()
typedef long double ld;
typedef long long ll;
ll _, n, m, k, s, x, y, p;
ll a[1001][1001];
ll st[1001][1001];
ll fin[1001][1001];
bool used[1001];
void solve();
int main() {
    cin >> _;
    while (_--) solve();
}
void solve() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        used[i] = 0;
        for (int j = 0; j < m; j++) {
            used[j] = 0;
            cin >> a[i][j];
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> st[j][i];
        }
    }
    for (int i = 0; i < n; i++) {
        for (int k = 0; k < n; k++) {
            if (used[k]) continue;
            for (int l = 0; l < m; l++) {
                if (a[k][l] == st[i][0]) {
                    for (int g = 0; g < m; g++) {
                        cout << a[k][g] << " ";
                    }
                    cout << endl;
                    used[k] = 1;
                    break;
                }
            }
            if (used[k]) break;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323846
#define E  2.71828182845904523536
#define pout(x) cout << fixed << setprecision(x)
#define INF INFINITY
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define siz(x) (ll)x.size()
#define all(x) x.begin(), x.end()
typedef long double ld;
typedef long long ll;
ll _, n, m, k, s, x, y, p;
ll a[1001][1001];
ll st[1001][1001];
ll fin[1001][1001];
void solve();
int main() {
    cin >> _;
    while(_--) solve();
}
ll gcd(ll a, ll b){
    return (b ? gcd(b, a % b) : a);
}
void solve() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> a[i][j];
            fin[i][j] = 0;
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> st[j][i];
        }
    }
    for(int i = 0; i < m; i++){
        for(int k = 0; k < m; k++){
            set<ll> sttt;
            for(int j = 0; j < n; j++){
                sttt.insert(a[j][i]);
                sttt.insert(st[j][k]);
            }
            if(sttt.size() == n){
                for(int j = 0; j < n; j++){
                    fin[j][k] = st[j][k];
                }
            }
        }
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cout << fin[i][j] << " ";
        }
        cout << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323846
#define E  2.71828182845904523536
#define pout(x) cout << fixed << setprecision(x)
#define INF INFINITY
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define siz(x) (ll)x.size()
#define all(x) x.begin(), x.end()
typedef long double ld;
typedef long long ll;
ll _, n, m, k, s, x, y, p;
ll a[1001][1001];
ll st[1001][1001];
ll fin[1001][1001];
bool used[1001];
void solve();
int main() {
    cin >> _;
    while (_--) solve();
}
void solve() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> a[i][j];
            fin[i][j] = 0;
            used[j] = 0;
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> st[j][i];
        }
    }
    for (int i = 0; i < m; i++) {
        for (int k = 0; k < m; k++) {
            if (used[k]) continue;
            set<ll> sttt;
            for (int j = 0; j < n; j++) {
                sttt.insert(a[j][i]);
                sttt.insert(st[j][k]);
            }
            if (siz(sttt) == n) {
                for (int j = 0; j < n; j++) {
                    fin[j][i] = st[j][k];
                }
                used[k] = 1;
            }
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << fin[i][j] << " ";
        }
        cout << endl;
    }
}