#include <cstdio>
#include <iostream>
#include <cassert>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int N = 100005, INF = 2100000000;

int n;
bool del[N];
vector<int> G[N];
int num[N], ind[N], Ind[N];
queue<int> z[3];

int test(int k){
	if(z[k].empty()) return INF;
	int rest = n;
	int ret = 0;
	while(rest){
		while(!z[k].empty()){
			int x = z[k].front(); z[k].pop();
			del[x] = true; rest--;
			for(int i = 0; i < G[x].size(); i++){
				int y = G[x][i];
				if(!del[y]){
					ind[y]--;
					if(ind[y] == 0) z[num[y]].push(y);
				}
			}
		}
		k = 3 - k;
		if(rest) ret++;
	}
	return ret;
}

void init(){
	memset(del, 0, sizeof(del));
	while(!z[1].empty()) z[1].pop();
	while(!z[2].empty()) z[2].pop();
	for(int i = 1; i <= n; i++){
		ind[i] = Ind[i];
		if(ind[i] == 0)
			z[num[i]].push(i);
	}
}

void clear(){
	memset(Ind, 0, sizeof(Ind));
	for(int i = 1; i <= n; i++) G[i].clear();
}

int main(){
	int cs;
	scanf("%d", &cs);
	while(cs--){
		int m;
		scanf("%d %d", &n, &m);
		clear();
		for(int i = 1; i <= n; i++)
			scanf("%d", num + i);
		while(m--){
			int a, b;
			scanf("%d %d", &a, &b);
			G[a].push_back(b);
			Ind[b]++;
		}
		init();
		int ans = test(1);
		init();
		ans = min(ans, test(2));
		printf("%d\n", ans);
	}
	return 0;
}
