#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define nl "\n"
#define ws " "
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define MOD 1000000007
typedef vector<int> vi;
typedef vector<pair<ll, ll>> vii;
const int MX = 2e5 + 2;
vector<vector<int>> G(MX);
vector<bool> vis (MX, false);
set<int> comp;
void dfs (int node) {
vis[node] = true;
comp.insert(node);
for (auto e: G[node]) {
if (!vis[e]) {
dfs (e);
}
}
}
int main () {
FASTIO
int t;
cin>>t;
while (t--) {
int n, q;
cin>>n>>q;
vi a (n + 1);
for (int i = 1; i <= n; i++) {
cin>>a[i];
}
for (int i = 0; i < q; i++) {
int u, v;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
dfs (i);
set<int> st;
for (auto e: comp) {
st.insert(a[e]);
}
int cnt = 0;
for (auto e: comp) {
if (st.find(e) != st.end()) {
cnt++;
}
}
ans += cnt;
comp.clear();
}
}
cout<<ans<<nl;
for (int i = 0; i <= n; i++) {
G[i].clear();
vis[i] = false;
}
}
return 0;
}