// CERC 2012 // Problem J: Conservation // Model solution. // Author: Jakub Pachocki import java.io.*; import java.util.*; import sun.misc.Queue; class Solver { void solve() throws IOException { Reader.init(System.in); int nCases = Reader.nextInt(); for (int testCase = 0; testCase < nCases; ++testCase) { int n = Reader.nextInt(); int m = Reader.nextInt(); int[] lab = new int[n]; for (int i = 0; i < n; ++i) { lab[i] = Reader.nextInt(); } ArrayList[] e = new ArrayList[n]; for (int i = 0; i < n; ++i) { e[i] = new ArrayList(); } for (int i = 0; i < m; ++i) { int a = Reader.nextInt(); int b = Reader.nextInt(); --a; --b; e[a].add(b); } int result = n; for (int start = 1; start <= 2; ++start) { int[] indeg = new int[n]; for (int i = 0; i < n; ++i) { for (int j: e[i]) { ++indeg[j]; } } java.util.Deque q = new ArrayDeque(); for (int i = 0; i < n; ++i) { if (indeg[i] == 0) { if (lab[i] == start) { q.addFirst(i); } else { q.addLast(i); } } } int curLab = start; int score = 0; while (!q.isEmpty()) { int c = q.poll(); if (lab[c] != curLab) { ++score; curLab = lab[c]; } for (int v: e[c]) { if (--indeg[v] == 0) { if (lab[v] == curLab) { q.addFirst(v); } else { q.addLast(v); } } } } result = Math.min(result, score); } System.out.println(result); } } } public class J { public static void main(String[] args) throws IOException { (new Solver()).solve(); } } /** Class for buffered reading int and double values */ class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }