Skip to content

Instantly share code, notes, and snippets.

@codegagan
Created August 20, 2018 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegagan/15882f98cd4c44d39dd9b0fa0d3949a7 to your computer and use it in GitHub Desktop.
Save codegagan/15882f98cd4c44d39dd9b0fa0d3949a7 to your computer and use it in GitHub Desktop.
Tree Diameter problem
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
class TestClass {
private final static Map<Integer, List<Integer>> map = new HashMap<>();
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N - 1; i++) {
String s = br.readLine();
String[] sa = s.split("\\s");
addEdge(sa[0], sa[1]);
}
IntStream.range(1, N + 1).map(in -> getMaxDistance(in)).forEach(p -> System.out.print(p + " "));
}
private static void addEdge(String value, String to) {
int node = Integer.parseInt(value);
int toNode = Integer.parseInt(to);
if (map.containsKey(node)) {
map.get(node).add(toNode);
} else {
List<Integer> a = new ArrayList<Integer>();
a.add(toNode);
map.put(node, a);
}
}
private static int getMaxDistance(int node) {
if (map.get(node) == null || map.get(node).size() < 1) {
return 0;
}
List<Integer> sortedHeight = map.get(node).stream().mapToInt(x -> height(x)).sorted().boxed()
.collect(Collectors.toList());
if (sortedHeight.size() == 1) {
return 1 + sortedHeight.get(sortedHeight.size() - 1);
} else if (sortedHeight.size() > 1) {
return 2 + sortedHeight.get(sortedHeight.size() - 1) + sortedHeight.get(sortedHeight.size() - 2);
}
//
// List<Integer> sorted = map.get(node).stream().mapToInt(x ->
// getMaxDistance(x)).sorted().boxed()
// .collect(Collectors.toList());
//
// if (sorted.size() == 1) {
// return 1 + sorted.get(sorted.size() - 1);
// } else if (sorted.size() > 1) {
// return 2 + sorted.get(sorted.size() - 1) + sorted.get(sorted.size() - 2);
// }
return 0;
}
private static int height(int node) {
if (map.get(node) == null || map.get(node).size() < 1) {
return 0;
}
return map.get(node).stream().mapToInt(x -> height(x)).max().getAsInt() + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment