|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.ArrayDeque; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.Queue; |
| 7 | +import java.util.StringTokenizer; |
| 8 | + |
| 9 | +public class boj_1005_ACM { |
| 10 | + |
| 11 | + public static void main(String[] args) throws IOException{ |
| 12 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + StringTokenizer st; |
| 14 | + int T = Integer.parseInt(br.readLine()); |
| 15 | + int N,K,W; |
| 16 | + int [] cost,dp; |
| 17 | + int [] indegree; |
| 18 | + ArrayList<Integer> [] graph; |
| 19 | + for(int tc = 0; tc<T; tc++){ |
| 20 | + st = new StringTokenizer(br.readLine()); |
| 21 | + N = Integer.parseInt(st.nextToken()); |
| 22 | + K = Integer.parseInt(st.nextToken()); |
| 23 | + cost = new int[N+1]; |
| 24 | + dp = new int[N+1]; |
| 25 | + indegree = new int[N+1]; |
| 26 | + graph = new ArrayList[N+1]; |
| 27 | + for(int i=1; i<=N; i++){ |
| 28 | + graph[i]=new ArrayList<>(); |
| 29 | + } |
| 30 | + st = new StringTokenizer(br.readLine()); |
| 31 | + for(int n=1; n<=N; n++){ |
| 32 | + cost[n] = Integer.parseInt(st.nextToken()); |
| 33 | + dp[n] = cost[n]; |
| 34 | + } |
| 35 | + for(int k=0; k<K; k++){ |
| 36 | + st= new StringTokenizer(br.readLine()); |
| 37 | + int from = Integer.parseInt(st.nextToken()); |
| 38 | + int to = Integer.parseInt(st.nextToken()); |
| 39 | + graph[from].add(to); |
| 40 | + indegree[to]++; |
| 41 | + } |
| 42 | + W = Integer.parseInt(br.readLine()); |
| 43 | + if(indegree[W]==0){ |
| 44 | + System.out.println(cost[W]); |
| 45 | + continue; |
| 46 | + } |
| 47 | + Queue<Integer> q= new ArrayDeque<>(); |
| 48 | + for(int i=1; i<=N; i++){ |
| 49 | + if(indegree[i]==0){ |
| 50 | + q.add(i); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + while (!q.isEmpty()) { |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + int cur = q.poll(); |
| 59 | + |
| 60 | + for(int next : graph[cur]){ |
| 61 | + dp[next]=Math.max(dp[next],dp[cur]+cost[next]); |
| 62 | + |
| 63 | + if(--indegree[next]==0){ |
| 64 | + q.offer(next); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + System.out.println(dp[W]); |
| 69 | + |
| 70 | + |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments