This page is still under construction.

Parts of this page are still being built. What you see may change.

Confuzzle

Time limit3sMemory limit1024 MB

Summary
Given a tree whose vertices carry labels, find the minimum distance between two vertices that share the same label.
Level

Medium7 of 10

Topics
Tree, DFS, Dynamic programming, Implementation
Solved
No attempts yet

Problem

You are given an unweighted tree with NN vertices. The distance between two vertices in the tree is defined as the number of edges on the path between them.

Each vertex has a number written on it, and at least two vertices are guaranteed to have the same number. Find the smallest possible distance between a pair of vertices that have the same number written on them.

Input

The first line contains the number of vertices in the tree, NN. (2≤N≤100 0002 \leq N \leq 100\ 000)

The second line contains NN integers c1,c2,⋯ ,cNc_1, c_2, \cdots, c_N, the distinct values of the vertices. (1≤ci≤N1 \leq c_i \leq N)

The next N−1N - 1 lines each contain two integers uu and vv describing an edge of the tree. This means that an edge connects vertex uu and vertex vv. (1≤u,v≤N1 \leq u, v \leq N, u≠vu \neq v)

Output

Print the smallest distance between a pair of vertices that have the same value.

Examples1

  1. Example 1

    Input
    7
    1 2 3 1 4 2 2
    1 2
    1 3
    3 4
    3 5
    4 6
    5 7
    
    Expected output
    2