/**
* author: Binoy Barman
* created: 2025-01-02 21:27:21
**/
#include<bits/stdc++.h>
#ifdef LOCAL
#include "debug/trace.hpp"
#else
#define dbg(...) 42
#define print(...) 42
#endif
using namespace std;
using ll = long long;
const int mod = 1e9 + 7;
const int inf = 1e9;
#define int long long
#define nl '\n'
#define all(v) v.begin(), v.end()
#define Testcase_Handler int tts, tc = 1; cin >> tts; hell: while(tts--)
#define uniq(v) sort(all(v)), v.resize(distance(v.begin(), unique(v.begin(), v.end())))
template<class T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;};
template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {bool first = true;for(auto &x : a) {if(!first) out << ' ';first = false;out << x;}return out;};
namespace Dark_Lord_Binoy {
void preprocess() {}
void setup() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
preprocess();
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
}
struct DSU {
vector<int> par, rank, sz;
int c;
DSU(int n) : par(n + 1), rank(n + 1, 0), sz(n + 1, 1), c(n) {
for (int i = 1; i <= n; i++) par[i] = i;
}
int find(int v) { // finding root of v
if(par[v] == v) return v;
else return par[v] = find(par[v]);
}
bool same(int a, int b) {
return find(a) == find(b);
}
int get_size(int v) {
return sz[find(v)];
}
int count() {
return c; // connected components
}
void merge(int a, int b) {
a = find(a), b = find(b);
if(a == b) return; // already in same component
else c--;
if(rank[a] > rank[b]) swap(a, b);
par[a] = b;
sz[b] += sz[a];
if(rank[a] == rank[b]) rank[b]++;
}
};
struct Dfs {
vector<vector<int>> g;
vector<int> con;
vector<bool> vis;
Dfs(int n) : vis(n + 1), g(n + 1) {}
void add_edge(int u, int v) {
g[u].push_back(v);
g[v].push_back(u);
}
void dfs(int v, int p = -1) {
vis[v] = true;
con.push_back(v);
for(auto u : g[v]) if(!vis[u]) {
dfs(u, v);
}
}
};
int32_t main() {
Dark_Lord_Binoy::setup();
Testcase_Handler {
int n, q;
cin >> n >> q;
vector<int> a(n + 1), pos(n + 1);
for (int i = 1; i <= n; i++) {
cin >> a[i];
pos[a[i]] = i;
}
Dfs g(n);
DSU c(n);
while(q--) {
int u, v;
cin >> u >> v;
g.add_edge(a[u], a[v]);
c.merge(u, v);
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if(!g.vis[i]) {
g.dfs(i);
vector<int> con = g.con;
g.con.clear();
for(auto x : con) {
if(c.same(pos[x], x)) {
ans++;
}
}
}
}
cout << ans << nl;
}
print(_Time_);
return 0;
}