#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 9;
struct DSU
{
vector<int> par, rnk, sz;
int c;
DSU(int n) : par(n + 1), rnk(n + 1, 0), sz(n + 1, 1), c(n)
{
for (int i = 1; i <= n; ++i)
par[i] = i;
}
int find(int i)
{
return (par[i] == i ? i : (par[i] = find(par[i])));
}
bool same(int i, int j)
{
return find(i) == find(j);
}
int get_size(int i)
{
return sz[find(i)];
}
int count()
{
return c; // connected components
}
int merge(int i, int j)
{
if ((i = find(i)) == (j = find(j)))
return -1;
else
--c;
if (rnk[i] > rnk[j])
swap(i, j);
par[i] = j;
sz[j] += sz[i];
if (rnk[i] == rnk[j])
rnk[j]++;
return j;
}
};
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n, q;
cin >> n >> q;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++)
cin >> a[i];
DSU dsu(n);
while (q--)
{
int x, y;
cin >> x >> y;
if (!dsu.same(x, y))
{
dsu.merge(x, y);
}
}
vector<int> ase, vis(n + 1, 0);
map<int, vector<pair<int, int>>> mp;
for (int i = 1; i <= n; i++)
{
// cout<<dsu.find(i)<<" ";
if (!vis[dsu.find(i)])
{
vis[dsu.find(i)] = 1;
ase.push_back(dsu.find(i));
}
mp[dsu.find(i)].push_back({i, a[i]});
}
int ans = 0;
for (auto x : mp)
{
sort(x.second.begin(), x.second.end());
set<int> st;
for (auto y : x.second)
{
st.insert(y.second);
}
for (auto y : x.second)
{
if (st.find(y.first) != st.end())
{
ans++;
}
}
}
cout << ans << '\n';
}
return 0;
}