#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int N = 2e5 + 5;
const int M = 2e3 + 5;
const int NUM_BLOCKS = (M / 64) + 2;
struct Bitset {
unsigned long long data[NUM_BLOCKS];
Bitset() {
memset(data, 0, sizeof(data));
}
void set_bit(int pos) {
data[pos >> 6] |= (1ULL << (pos & 63));
}
int count() {
int res = 0;
for (int i = 0; i < NUM_BLOCKS; ++i) {
res += __builtin_popcountll(data[i]);
}
return res;
}
void update(const Bitset &Match) {
unsigned long long borrow = 0;
unsigned long long carry_shift = 1;
for (int i = 0; i < NUM_BLOCKS; ++i) {
unsigned long long X = data[i] | Match.data[i];
unsigned long long shifted = (data[i] << 1) | carry_shift;
carry_shift = (data[i] >> 63);
unsigned long long Y = shifted;
unsigned long long diff = X - Y - borrow;
if (X < Y || (X == Y && borrow)) {
borrow = 1;
} else {
borrow = 0;
}
data[i] = X & (X ^ diff);
}
}
};
int n, m;
int a[N], b[M];
Bitset P[M + 5];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t;
if (!(cin >> t)) return 0;
while (t--) {
cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> a[i];
map<int, int> compress;
int distinct_count = 0;
for (int i = 1; i <= m; ++i) {
cin >> b[i];
if (compress.find(b[i]) == compress.end()) {
compress[b[i]] = ++distinct_count;
memset(P[distinct_count].data, 0, sizeof(P[distinct_count].data));
}
P[compress[b[i]]].set_bit(i - 1);
}
Bitset D;
static Bitset empty_mask;
memset(empty_mask.data, 0, sizeof(empty_mask.data));
for (int i = 1; i <= n; ++i) {
if (compress.find(a[i]) == compress.end()) {
D.update(empty_mask);
} else {
D.update(P[compress[a[i]]]);
}
}
cout << D.count() << '\n';
}
return 0;
}