#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
void dfs(int vertex,vector<bool>&visited,vector<vector<int>>&graph,vector<int>&tempCC_Storage,vector<vector<int>>&connectedComponentsStorage){
tempCC_Storage.push_back(vertex);
visited[vertex]=true;
for(auto child:graph[vertex]){
if(visited[child])continue;
dfs(child,visited,graph,tempCC_Storage,connectedComponentsStorage);
}
}
vector<int> takeVectorInput(int n){
vector<int>v(n+1);
for(int i=1;i<=n;++i) {
cin>>v[i];
}
return v;
}
int main(){
int t;
cin>>t;
while(t--){
int n,e;
cin>>n>>e;
auto v=takeVectorInput(n);
vector<vector<int>> graph(n+1);
vector<bool>visited(n+1,false);
for(int i=0;i<e;++i){
int n1,n2;
cin>>n1>>n2;
graph[n1].push_back(n2);
graph[n2].push_back(n1);
}
vector<vector<int>> connectedComponentsStorage;
int countOfComponents=0;
for(int i=1;i<=n;++i){
if(visited[i])continue;
vector<int> tempCC_Storage;
dfs(i,visited,graph,tempCC_Storage,connectedComponentsStorage);
connectedComponentsStorage.push_back(tempCC_Storage);
countOfComponents++;
}
// cout<<countOfComponents<<endl;
int ans=0;
for(auto components:connectedComponentsStorage){
// vector<int> temp;
map<int,int> mp;
for(auto ele:components){
if(v[ele]==ele)continue;
mp[v[ele]]++;
}
int cnt=0;
for(auto ele:components){
if(mp[ele])cnt++;
}
ans+=cnt;
// cout<<endl;
}
for(int i=1;i<=n;++i){
if(v[i]==i)ans++;
}
cout<<ans<<endl;
}
}
// Sample input:
// 8 5
// 1 2
// 2 3
// 2 4
// 3 5
// 6 7
// Sample Output:
// 3