#include <bits/stdc++.h>
using namespace std;
int main() {
  int t, n, m, y;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    int a[n][m];
    map<int, int> ma;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
        if (j == 0) {
          ma[a[i][j]] = i + 1;
        }
      }
    }
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        cin >> y;
        if (ma[y] != 0) {
          for (int k = 0; k < m; ++k) {
            cout << a[ma[y] - 1][k] << " ";
          }
          cout << endl;
        }
      }
    }
  }
}
