Home BOJ. Diameter of Tree (1167)
Post
Cancel

BOJ. Diameter of Tree (1167)

[Link] https://www.acmicpc.net/problem/1167


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static int max = 0, maxIdx = 0;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;
		int v = toi(br.readLine());
		Node[] nodes = new Node[v];
		boolean[] visit = new boolean[v];

		for(int i = 0; i < v; i++) nodes[i] = new Node(i);

		for(int i = 0; i < v; i++) {
			line = getLine();
			int cur = 1, v1 = toi(line[0]) - 1;
			while(true) {
				int v2 = toi(line[cur++]) - 1;
				if(v2 == -2) break;
				int dis = toi(line[cur++]);
				nodes[v1].adj.add(new int[] { v2, dis });
				nodes[v2].adj.add(new int[] { v1, dis });
			}
		}
		visit[0] = true;
		dfs(nodes, visit, 0, 0);
		Arrays.fill(visit, false);
		visit[maxIdx] = true;
		dfs(nodes, visit, 0, maxIdx);
		print(max);
	}

	static void dfs(Node[] nodes, boolean[] visit, int len, int cur) {
		if(len > max) {
			max = len;
			maxIdx = cur;
		}
		for(int[] arr: nodes[cur].adj) {
			if(visit[arr[0]]) continue;
			visit[arr[0]] = true;
			dfs(nodes, visit, len + arr[1], arr[0]);
		}
	}

	public static class Node {
		int idx;
		ArrayList<int[]> adj;

		Node(int idx) { this.idx = idx; this.adj = new ArrayList<int[]>(); }
	}


	static int sum(int[] arr, int s, int e) { int sum = 0; for(int i = s; i <= e; i++) sum+=arr[i]; return sum; }
	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.