1 -> 2, 3 -> 4 ์ 5 -> 4 2๊ฐ์ง ๊ฒฝ๋ก๊ฐ ์กด์ฌํ ์ ์๋ค.
์ด๋ ๋งค ๋ ธ๋๋ง๋ค ๊ฑธ๋ฆฌ๋ ์๊ฐ๋ค์ ๊ฐฑ์ ํด์ผ ํ๋ค. 2, 3์ ๊ฒฝ์ฐ 1์ด๋ผ๋ ๊ฐ์ ์ถ๋ฐ์ง๋ฅผ ๊ฐ๊ณ ์๊ธฐ ๋๋ฌธ์ 30๊ณผ 40์ ์๊ฐ์ด ์ต์๋ก ๊ฑธ๋ฆฌ๊ฒ ๋๋ค.
์ด์ 4๋ 2, 3, 5 ์ค ํ๋์์ ๋๋ฌํ ์ ์๊ฒ ๋๋๋ฐ, ์ด๋ ๊ฑธ๋ฆฌ๋ ์๊ฐ์ ์ต์๊ฐ์ ๊ตฌํ๋ผ๊ณ ํ์ง๋ง ์ค์ ๋ก๋ 2, 3, 5๊ฐ ๋ชจ๋ ๊ฑด์ค๋์ด์ผ 4๊ฐ ๊ฑด์ค๋ ์ ์์ผ๋ฏ๋ก ๊ฒฐ๊ตญ 2, 3, 5๊ฐ ๋ชจ๋ ๊ฑด์ค๋ ์ ์๋ ์๊ฐ ์ฆ 2, 3, 5 ์ค ๊ฑด์ค ์๊ฐ์ ์ต๋๊ฐ์ ๊ตฌํด์ผ ํ๋ค. ๊ทธ ์ต๋๊ฐ์ 4์ ๊ฑด์ค๋ ์๊ฐ์ ๋ํ๋ฉด ๋๋ค.
๊ฒฐ๊ตญ ๋ชฉ์ ๋ ธ๋์ ๋๋ฌํ ์ ์๋ ์ ํ ๋ ธ๋๋ค ๊ฐ์ด๋ฐ ์ต๋๊ฐ์ ๊ตฌํ๊ณ ๊ทธ ๊ฐ๊ณผ ๋ชฉ์ ๋ ธ๋์ ๊ฑด์ค ์๊ฐ์ ๋ํด์ ๊ตฌํ ์ ์๋ค.
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static int solution() throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int[] builtTime = new int[N+1];
int[] connectCount = new int[N+1];
List<List<Integer>> builtOrder = new ArrayList<>();
for (int i = 0; i <= N; i++) {
builtOrder.add(new ArrayList<>());
}
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
builtTime[i] = Integer.parseInt(st.nextToken());
}
int X;
int Y;
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
X = Integer.parseInt(st.nextToken());
Y = Integer.parseInt(st.nextToken());
connectCount[Y]++;
builtOrder.get(X).add(Y);
}
int W = Integer.parseInt(br.readLine());
Queue<Integer> queue = new LinkedList<>();
for (int i = 1; i <= N; i++) {
if (connectCount[i] == 0) {
queue.add(i);
}
}
int[] answer = Arrays.copyOf(builtTime, N+1);
while (!queue.isEmpty()) {
Queue<Integer> nextQueue = new LinkedList<>();
while (!queue.isEmpty()) {
int w = queue.poll();
int timeW = answer[w];
for (int nextW : builtOrder.get(w)) {
connectCount[nextW]--;
answer[nextW] = Math.max(answer[nextW], builtTime[nextW] + timeW);
if (connectCount[nextW] == 0) {
nextQueue.add(nextW);
}
}
}
queue = nextQueue;
}
return answer[W];
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < T; i++) {
sb.append(solution() + "\n");
}
sb.replace(sb.length()-1, sb.length(), "");
System.out.println(sb);
}
}