#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m, tmp;
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m)), b(m, vector<int>(n));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> a[i][j];
    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++) cin >> b[i][j];
    bool s = false;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (a[i][j] == b[0][0]) {
          for (int o = 0; o < n; o++) {
            if (a[o][j] != b[0][o]) {
              for (int u = 0; u < n; u++) {
                if (a[o][j] == b[0][u]) {
                  swap(a[o], a[u]);
                  o = 0;
                  break;
                }
              }
            }
          }
          s = true;
          break;
        }
      }
      if (s) break;
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cout << a[i][j] << ' ';
      }
      cout << '\n';
    }
  }
  return 0;
}
