1 #include<stdio.h> 2 const int N = 1010; 3 int pref[N][N], order[N][N], next[N]; 4 int fh[N], fw[N]; 5 int q[N * 100], rear, front; 6 void engage(int man, int woman) { 7 int m = fh[woman]; 8 if(m) { 9 fw[m] = 0; 10 q[++rear] = m; 11 } 12 fw[man] = woman; 13 fh[woman] = man; 14 } 15 int main() { 16 int t; 17 scanf("%d", &t); 18 while(t--) { 19 rear = -1; front = 0; 20 int n; 21 scanf("%d", &n); 22 for(int i = 1; i <= n; ++i) { 23 for(int j = 1; j <= n; ++j) 24 scanf("%d", &pref[i][j]); 25 next[i] = 1; 26 fw[i] = 0; 27 q[++rear] = i; 28 } 29 for(int i = 1; i <= n; ++i) { 30 for(int j = 1; j <= n; ++j) { 31 int x; 32 scanf("%d", &x); 33 order[i][x] = j; 34 } 35 fh[i] = 0; 36 } 37 while(front <= rear) { 38 int man = q[front++]; 39 int woman = pref[man][next[man]++]; 40 if(!fh[woman]) engage(man, woman); 41 else if(order[woman][man] < order[woman][fh[woman]]) engage(man, woman); 42 else q[++rear] = man; 43 } 44 for(int i = 1; i <= n; ++i) printf("%d\n", fw[i]); 45 if(t) printf("\n"); 46 } 47 return 0; 48 }