• 문제 링크
10552번: DOM
The first line of input contains three integers N, M and P (1 ≤ N, M ≤ 105, 1 ≤ P ≤ M), the number of pensioners, the number of TV channels and the initial channel displayed on TV. Each of the following N lines contains two integers ai and bi (1
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
static int[] arr;
static boolean[] visit;
static int cnt = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
arr = new int[m + 1];
visit = new boolean[m + 1];
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if (arr[b] == 0)
arr[b] = a;
}
dfs(p);
bw.write(String.valueOf(cnt));
bw.flush();
}
private static void dfs(int idx) {
if (visit[idx]) {
cnt = -1;
return;
}
if (arr[idx] > 0) {
visit[idx] = true;
cnt++;
dfs(arr[idx]);
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 7662 이중 우선순위 큐 - Data Structure / Java (0) | 2023.04.23 |
---|---|
[백준] 4677 Oil Deposits - Graph Theory / Java (0) | 2023.04.22 |
[백준] 6186 Best Grass - Graph Theory / Java (0) | 2023.04.20 |
[백준] 17198 Bucket Brigade - Graph Theory / Java (0) | 2023.04.19 |
[백준] 18243 Small World Network - Graph Theory / Java (0) | 2023.04.19 |
댓글