728x90
반응형
https://www.acmicpc.net/problem/1005
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static int[] seq;
static int[] value;
static int[] dp;
static ArrayList<ArrayList<Integer>> grapgh;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int T = Integer.parseInt(br.readLine());
while(T --> 0) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
seq = new int[N + 1];
value = new int[N + 1];
dp = new int[N + 1];
grapgh = new ArrayList<>();
for (int i = 0; i < N + 1; i++) {
grapgh.add(new ArrayList<>());
}
st = new StringTokenizer(br.readLine());
for (int i = 1; i < N + 1; i++) {
value[i] = Integer.parseInt(st.nextToken());
}
while(M --> 0) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
seq[v]++;
grapgh.get(u).add(v);
}
int destination = Integer.parseInt(br.readLine());
sb.append(topologicalSort(destination)).append("\n");
}
System.out.println(sb.toString());
}
static int topologicalSort(int destination) {
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i < seq.length; i++) {
if(seq[i] == 0) {
q.offer(i);
dp[i] = value[i];
}
}
while (!q.isEmpty()) {
int cur = q.poll();
if (seq[destination] == 0) {
break;
}
for(int next : grapgh.get(cur)) {
seq[next]--;
dp[next] = Math.max(dp[next], value[next] + dp[cur]);
if(seq[next] == 0) {
q.offer(next);
}
}
}
return dp[destination];
}
}
|
cs |
728x90
'Algorithm > BOJ' 카테고리의 다른 글
백준) 1074_Z (0) | 2023.05.16 |
---|---|
백준) 11003_최솟값 찾기 (2) | 2023.05.14 |
백준) 21276_계보 복원가 호석 (2) | 2023.05.13 |
백준) 1766_문제집 (1) | 2023.05.13 |
백준) 14676_영우는 사기꾼? (2) | 2023.05.13 |