-
Notifications
You must be signed in to change notification settings - Fork 6
/
dongwoo.java
49 lines (45 loc) · 1.18 KB
/
dongwoo.java
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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class dongwoo {
public static void main(String[] args) {
// 시작 2:25 끝 2:47
Scanner sc = new Scanner(System.in);
HashMap<Integer, Integer> bottomUp = new HashMap<Integer, Integer>();
int n = sc.nextInt();
int from = sc.nextInt();
int to = sc.nextInt();
int connections = sc.nextInt();
for (int i = 0; i < connections; i++) {
int p = sc.nextInt();
int c = sc.nextInt();
bottomUp.put(c, p);
}
ArrayList<Integer> pOfFrom = new ArrayList<Integer>();
ArrayList<Integer> pOfTo = new ArrayList<Integer>();
int now = from;
pOfFrom.add(now);
while (bottomUp.containsKey(now)) {
pOfFrom.add(bottomUp.get(now));
now = bottomUp.get(now);
}
now = to;
pOfTo.add(now);
while (bottomUp.containsKey(now)) {
pOfTo.add(bottomUp.get(now));
now = bottomUp.get(now);
}
boolean isFamily = false;
for (int i:pOfTo) {
Integer Wrapper = Integer.valueOf(i);
if (pOfFrom.contains(Wrapper)) {
System.out.println(pOfFrom.indexOf(Wrapper)+pOfTo.indexOf(Wrapper));
isFamily = true;
break;
}
}
if (!isFamily) {
System.out.println(-1);
}
}
}