#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int z = 0; z < t; ++z) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a(n, vector<int>(m));
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
      }
    }
    vector<vector<int>> b(n, vector<int>(m));
    for (int j = 0; j < m; ++j) {
      for (int i = 0; i < n; ++i) {
        cin >> b[i][j];
      }
    }
    for (int i = 0; i < n; ++i) {
      int temp = b[i][0];
      for (int j = 0; j < n; ++j) {
        for (int y = 0; y < m; ++y) {
          if (a[j][y] == temp) {
            for (int x = 0; x < m; ++x) {
              cout << a[j][x] << ' ';
            }
            cout << endl;
            break;
          }
        }
      }
    }
  }
}
