Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Main {
- static Map<Integer, Vertex> distances = new HashMap<>();
- static int max = 0;
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int N = in.nextInt();
- List<Vertex> vertices = new ArrayList<>();
- List<Vertex> leaves = new ArrayList<>();
- for (int i = 0; i < N; i++) {
- Vertex current = new Vertex(in.nextInt());
- vertices.add(current);
- leaves.add(current);
- }
- for (int i = 0; i < N - 1; i++) {
- Vertex one = vertices.get(in.nextInt() - 1);
- Vertex two = vertices.get(in.nextInt() - 1);
- one.addLink(two);
- two.addLink(one);
- if (one.getLinks() > 1) {
- leaves.remove(one);
- }
- if (two.getLinks() > 1) {
- leaves.remove(two);
- }
- }
- dfs(leaves.get(0), null, leaves.get(0).value);
- Vertex start = distances.get(max);
- dfs(start, null, start.value);
- System.out.println(max);
- }
- private static void dfs(Vertex vertex, Vertex parent, int distance) {
- List<Vertex> links = vertex.links;
- for (Vertex link :
- links) {
- if (link.equals(parent)){
- distances.put(distance, vertex);
- max = Math.max(max, distance);
- continue;
- }
- dfs(link, vertex, distance + link.value);
- }
- }
- static class Vertex{
- List<Vertex> links = new ArrayList<>();
- int value;
- public Vertex(){
- }
- public Vertex(int value){
- setValue(value);
- }
- void setValue(int value){
- this.value = value;
- }
- void addLink(Vertex link){
- links.add(link);
- }
- int getLinks(){
- return links.size();
- }
- }
- }
Add Comment
Please, Sign In to add comment