#include <bits/stdc++.h>
using namespace std;
#define SC scanf
#define PF printf
#define ull unsigned long long
#define ld long double
#define F first
#define S second
#define pb push_back
#define sort_a(a) sort(a.begin(),a.end());
#define sort_d(a) sort(a.rbegin(),a.rend());
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define rev(s) reverse(s.begin(),s.end())
#define P(ok) cout << (ok ? "YES\n": "NO\n")
#define __Heart__ ios_base :: sync_with_stdio(false); cin.tie(NULL);
#define ll long long
typedef pair< ll , ll> PII;
const int sz = 1e5 + 5 ;
int n , q , x , y, a[sz] , point[sz] ;
vector < int > Edge[sz] ;
bool vis[sz] ;
void dfs(int id , int p) {
vis[id] = true ; point[id] = p ;
for(auto child : Edge[id]){
if(!vis[child]) dfs(child , p) ;
}
}
void solve()
{
cin >> n >> q ;
for(int i = 1 ; i <= n ; i++) cin >> a[i] ,point[i] = vis[i] = 0 , Edge[i].clear() ;
while(q--){
cin >> x >> y ;
Edge[x].pb(y) ;
Edge[y].pb(x) ;
}
int p = 1 , Ans = 0;
for(int i = 1 ; i <= n ; i++) if(!vis[i]) dfs(i , p++) ;
for(int i = 1 ; i <= n ; i++) if(point[i] == point[a[i]]) Ans++ ;
cout << Ans << "\n" ;
}
int main()
{
__Heart__
// READ("input2.txt") ;
// WRITE("output2.txt") ;
int t ; cin >> t ; while(t--) solve() ;
}