• 문제 링크
21937번: 작업
민상이가 작업할 개수 $N$와 작업 순서 정보의 개수 $M$이 공백으로 구분되어 주어진다. 두 번째줄부터 $M + 1$ 줄까지 작업 $A_i$와 작업 $B_i$가 공백으로 구분되어 주어진다. 이때 두 값의 의미는 작
www.acmicpc.net
• 풀이 코드
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Main {
static Node[] graph;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = read(), m = read();
graph = new Node[++n];
visit = new boolean[n];
while (n-- > 1) graph[n] = new Node(n);
while (m-- > 0) {
n = read();
graph[read()].addEdge(n);
}
bw.write(String.valueOf(dfs(read())));
bw.flush();
}
private static int dfs(int src) {
visit[src] = true;
int cnt = 0;
for (int tgt : graph[src].adj) if (!visit[tgt]) cnt += dfs(tgt) + 1;
return cnt;
}
private static class Node {
int src;
List<Integer> adj;
Node(int src) {
this.src = src;
this.adj = new ArrayList<>();
}
public void addEdge(int tgt) {
adj.add(tgt);
}
}
private static int read() throws IOException {
int c, n = System.in.read() & 15;
while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 9311 Robot in a Maze - Graph Theory / Java (0) | 2023.09.16 |
---|---|
[백준] 13700 완전 범죄 - Graph Theory / Java (0) | 2023.09.15 |
[백준] 11370 Spawn of Ungoliant - Graph Theory / Java (0) | 2023.09.13 |
[백준] 14544 Vote - Data Structure / Java (0) | 2023.09.12 |
[백준] 11235 Polling - Data Structure / Java (0) | 2023.09.11 |
댓글