#include <bits/stdc++.h>
using namespace std;
bool ok(const vector<int>& list1, const vector<int>& list2) {
unordered_set<int> digits1(list1.begin(), list1.end());
unordered_set<int> digits2(list2.begin(), list2.end());
for (int date = 1; date <= 31; ++date) {
int tens = date / 10;
int units = date % 10;
if (digits1.find(tens) == digits1.end() || digits2.find(units) == digits2.end()) {
return false;
}
}
return true;
}
int main() {
int t ; cin >> t ;
while(t--){
int n , m ; cin >> n >> m ;
vector<int> v(n) ,vr(m);
for(int i=0;i<n;i++) cin >>v[i];
for(int i=0;i<m;i++) cin >> vr[i] ;
if (ok(v, vr)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}