View difference between Paste ID: VGUC7Ra7 and hcbPEHiT
SHOW: | | - or go back to the newest paste.
1
import java.util.*;
2
3
4
public class Main {
5
    static Map<Integer, Vertex> distances = new HashMap<>();
6
    static int max = 0;
7
    public static void main(String[] args) {
8
        Scanner in = new Scanner(System.in);
9
        int N = in.nextInt();
10
        List<Vertex> vertices = new ArrayList<>();
11
        List<Vertex> leaves = new ArrayList<>();
12
        for (int i = 0; i < N; i++) {
13
            Vertex current = new Vertex(in.nextInt());
14
            vertices.add(current);
15
            leaves.add(current);
16
        }
17
        for (int i = 0; i < N - 1; i++) {
18
            Vertex one = vertices.get(in.nextInt() - 1);
19
            Vertex two = vertices.get(in.nextInt() - 1);
20
            one.addLink(two);
21
            two.addLink(one);
22
            if (one.getLinks() > 1) {
23
                leaves.remove(one);
24
            }
25
            if (two.getLinks() > 1) {
26
                leaves.remove(two);
27
            }
28
        }
29
30
        dfs(leaves.get(0), null, leaves.get(0).value);
31
32
        Vertex start = distances.get(max);
33
        dfs(start, null, start.value);
34
        System.out.println(max);
35
36
    }
37
38
    private static void dfs(Vertex vertex, Vertex parent, int distance) {
39
        List<Vertex> links = vertex.links;
40
        for (Vertex link :
41
                links) {
42
            if (link.equals(parent)){
43
                distances.put(distance, vertex);
44
                max = Math.max(max, distance);
45
                continue;
46
            }
47
            dfs(link, vertex, distance + link.value);
48
        }
49
50
    }
51
52
    static class Vertex{
53
        List<Vertex> links = new ArrayList<>();
54
        int value;
55
56
        public Vertex(){
57
        }
58
        public Vertex(int value){
59
            setValue(value);
60
        }
61
62
        void setValue(int value){
63
            this.value = value;
64
        }
65
66
        void addLink(Vertex link){
67
            links.add(link);
68
        }
69
70
        int getLinks(){
71
            return links.size();
72
        }
73
    }
74
}