#include <bits/stdc++.h>
using namespace std;
vector<int> tv;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> v(n, vector<int>(m));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> v[i][j];
    tv.resize(n);
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) cin >> tv[j];
      bool suc = false;
      for (int i = 0; i < n; i++)
        if (v[i][0] == tv[0]) suc = true;
      if (suc) {
        vector<int> od(n);
        for (int i = 0; i < n; i++)
          for (int j = 0; j < n; j++)
            if (v[j][0] == tv[i]) od[i] = j;
        for (int i = 0; i < n; i++)
          for (int j = 0; j < m; j++) cout << v[od[i]][j] << " \n"[j == m - 1];
      }
    }
  }
  return 0;
}
