#include <bits/stdc++.h>
using namespace std;
int n, m;
int row[505][505], col[505][505];
int idx[250005];
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> row[i][j];
        if (j == 1) {
          idx[row[i][j]] = i;
        }
      }
    }
    for (int j = 1; j <= m; j++) {
      for (int i = 1; i <= n; i++) {
        cin >> col[j][i];
      }
    }
    int id = 0;
    for (int f = 1; f <= m; f++) {
      for (int ff = 1; ff <= n; ff++) {
        if (col[f][1] == row[ff][1]) {
          id = f;
          break;
        }
      }
    }
    for (int k = 1; k <= n; k++) {
      for (int x = 1; x <= m; x++) {
        cout << row[idx[col[id][k]]][x] << ' ';
      }
      cout << endl;
    }
  }
  return 0;
}
