#include <bits/stdc++.h>
int main() {
  int n1, n2, n3, n4;
  std::cin >> n1;
  for (int i = 0; i < n1; i++) {
    std::cin >> n2 >> n3;
    std::map<int, int> m1;
    std::vector<std::vector<int>> v1(n3);
    for (int i = 0; i < n2; i++)
      for (int j = 0; j < n3; j++) std::cin >> n4, m1[n4] = j;
    for (int i = 0; i < n3; i++)
      for (int j = 0; j < n2; j++) std::cin >> n4, v1[m1[n4]].push_back(n4);
    for (int i = 0; i < n2; i++) {
      for (int j = 0; j < n3; j++) std::cout << v1[j][i] << " ";
      std::cout << "\n";
    }
  }
}
