-
Notifications
You must be signed in to change notification settings - Fork 0
/
BishuAndHisGirlFriend.java
66 lines (61 loc) · 1.85 KB
/
BishuAndHisGirlFriend.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/bishu-and-his-girlfriend/
* tag: #dfs #bfs use BFS / DFS (stack/ recursion)
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
class BishuAndHisGirlFriend {
static int callDFSRecursion(
int startNode,
ArrayList<ArrayList<Integer>> graph,
boolean[] visitedArr,
boolean[] girlArr,
HashMap<Integer, Integer> result) {
int dist = 0;
visitedArr[startNode] = true;
if (girlArr[startNode]) {
dist += 1;
if (result.containsKey(dist)) {
if (startNode < result.get(dist)) {
result.replace(dist, startNode);
}
} else {
result.put(dist, startNode);
}
}
if (!graph.get(startNode).isEmpty()) {
for (int node : graph.get(startNode)) {
if (!visitedArr[node]) {
dist += callDFSRecursion(node, graph, visitedArr, girlArr, result);
}
}
}
return dist;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(n + 1);
for (int i = 0; i < n + 1; i++) {
graph.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
int q = sc.nextInt();
boolean[] girlArr = new boolean[n + 1];
for (int i = 0; i < q; i++) {
int g = sc.nextInt();
girlArr[g] = true;
}
boolean[] visitedArr = new boolean[n + 1];
HashMap<Integer, Integer> result = new HashMap<>();
callDFSRecursion(1, graph, visitedArr, girlArr, result);
System.out.println(result.get(Collections.min(result.keySet())));
}
}