-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main2.java
59 lines (47 loc) Β· 1.5 KB
/
Main2.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
package Tree.P1167;
import java.io.*;
import java.util.*;
public class Main2 {
static int V, root, ans;
static ArrayList<Node>[] tree;
static boolean[] visited;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/Tree/P1167/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
V = Integer.parseInt(br.readLine());
tree = new ArrayList[V+1];
for (int i = 1; i <= V; i++) tree[i] = new ArrayList<>();
for (int i = 0; i < V; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken()), to, dist;
while ((to = Integer.parseInt(st.nextToken())) != -1) {
dist = Integer.parseInt(st.nextToken());
tree[from].add(new Node(to, dist));
}
}
visited = new boolean[V+1];
dfs(1, 0);
dfs(root, 0);
System.out.println(ans);
}
static void dfs(int now, int dist) {
visited[now] = true;
for (Node next : tree[now]) {
if (!visited[next.idx]) {
dfs(next.idx, dist + next.dist);
}
}
visited[now] = false;
if (ans < dist) {
ans = dist;
root = now;
}
}
static class Node {
int idx, dist;
public Node(int idx, int dist) {
this.idx = idx;
this.dist = dist;
}
}
}