#include <bits/stdc++.h>
using i64 = long long;
void solve() {
int n, q;
std::cin >> n >> q;
std::vector<int> a(n);
for (int i = 0; i < n; i++) {
std::cin >> a[i];
a[i]--;
}
std::vector<int> pa(n), sz(n);
std::iota(pa.begin(), pa.end(), 0);
std::fill(sz.begin(), sz.end(), 1);
auto find = [&](int x) {
int cur = x;
while (x != pa[x]) {
x = pa[x];
}
if (cur != x) {
pa[cur] = x;
}
return x;
};
auto merge = [&](int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (sz[x] < sz[y]) {
std::swap(x, y);
}
pa[y] = x;
sz[x] += sz[y];
return true;
};
for (int i = 0; i < q; i++) {
int l, r;
std::cin >> l >> r;
l--;
r--;
merge(l, r);
}
std::unordered_map<int, std::vector<int>> g;
for (int u = 0; u < n; u++) {
g[find(u)].push_back(u);
}
int ans = 0;
for (auto [_, gr] : g) {
std::unordered_set<int> s;
for (auto i : gr) {
s.insert(a[i]);
}
for (auto i : gr) {
if (s.contains(i)) {
ans++;
}
}
}
std::cout << ans << "\n";
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
int t;
std::cin >> t;
while (t--) {
solve();
}
}