#include <iostream>
#include <string>
using namespace std;
class Node
{
private:
Node *parent, *left, *right;
int elem;
public:
Node() = delete;
Node(int elem): elem{elem}, parent{nullptr}, left{nullptr}, right{nullptr} {}
~Node() = default;
friend class BST;
};
class BST
{
private:
Node* root;
int n; // size
void release(Node* node);
bool is_external(Node* node) const { return node->left == nullptr && node->right == nullptr; }
void pre_order(Node* node) const;
int erase(Node* erase);
void link(Node* u, Node* v); // u의 parent랑 v랑 연결(u는 항상 노드이고, v는 nullptr일 수 있음)
Node* get_minimum(Node* node);
public:
BST() : root{nullptr}, n{0} {}
~BST() { if(root != nullptr) release(root); }
bool empty() const { return n == 0; }
int size() const { return n; }
void insert(int x);
Node* find(int x) const;
void pre_order() const;
int erase(int x);
};
int main()
{
int T; cin >> T;
while(T--){
BST bst{};
int N; cin >> N;
for(int i = 0 ; i < N; i++){
int tmp; cin >> tmp;
bst.insert(tmp);
}
int M; cin >> M;
for(int i = 0; i < M; i++){
int tmp; cin >> tmp;
bst.erase(tmp);
}
bst.pre_order();
}
return 0;
}
Node* BST::get_minimum(Node* node)
{
while(node->left != nullptr){
node = node->left;
}
return node;
}
void BST::link(Node* u, Node* v)
{
// parent
if(u->parent == nullptr){
root = v;
}
else if(u->parent->left == u) u->parent->left = v;
else u->parent->right = v;
// child
if(v != nullptr) v->parent = u->parent;
}
Node* BST::find(int x) const
{
if(empty()) throw "error from BST::find";
Node* cur = root;
while(cur != nullptr){
if(cur->elem == x) return cur;
else if(cur->elem < x) cur = cur->right;
else cur = cur->left;
}
return cur; // doesn't exist
}
void BST::release(Node* node)
{
if(node->left != nullptr) release(node->left);
if(node->right != nullptr) release(node->right);
delete node; node = nullptr;
}
void BST::insert(int x)
{
Node* node = new Node{x};
if(empty()){
root = node;
}
else{
Node *cur = root, *prev = nullptr;
while(cur != nullptr){
prev = cur;
cur = ((cur->elem <= x)? cur->right: cur->left);
}
// parent
if(prev->elem <= x) prev->right = node;
else prev->left = node;
// child
node->parent = prev;
}
n += 1;
}
void BST::pre_order(Node* node) const
{
cout << node->elem << ' ';
if(node->left != nullptr) pre_order(node->left);
if(node->right != nullptr) pre_order(node->right);
}
void BST::pre_order() const
{
if(empty()) cout << 0 << endl;
else {
pre_order(root);
cout << endl;
}
}
int BST::erase(Node* z)
{
int ret = z->elem;
if(z->left == nullptr) link(z, z->right);
else if(z->right == nullptr) link(z, z->left);
else{
Node* y = get_minimum(z->right);
if(z != y->parent){
link(y, y->right);
y->right = z->right;
z->right->parent = y;
}
link(z, y);
y->left = z->left;
z->left->parent = y;
}
delete z; z = nullptr;
n -= 1;
return ret;
}
int BST::erase(int x)
{
if(empty()) throw "error from BST:erase";
Node* tar = find(x);
if(tar == nullptr) throw "error from BST::erase";
return erase(tar);