#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    bool ok = true;
    int n, m;
    cin >> n >> m;
    int a[n][m];
    int maxim = 0;
    int b[n];
    for (int j = 0; j < n; ++j) {
      for (int k = 0; k < m; ++k) {
        cin >> a[j][k];
        if (ok) {
          maxim = a[j][k];
          ok = false;
        }
      }
    }
    ok = true;
    for (int j = 0; j < m; ++j) {
      for (int k = 0; k < n; ++k) {
        cin >> b[k];
        if (b[k] == maxim) ok = false;
      }
      if (!ok) {
        for (int k = 0; k < n; ++k) {
          int ind = 0;
          for (ind; ind < n; ++ind) {
            if (a[ind][0] == b[k]) break;
          }
          for (int q = 0; q < m; ++q) {
            cout << a[ind][q] << ' ';
          }
          cout << '\n';
        }
        ok = true;
      }
    }
  }
  return 0;
}
