SnowflakeOA #43
Radio Waves
Estimated MediumJudge-ready
Topics (AI-labelled)Union-FindTree Paths
Device connections form a tree, and each frequency is 1, 2, or 3. An edge can carry signals if the absolute difference of its endpoints' frequencies is ≤1, and every edge along a path must be compatible. Find the maximum number of edges between any two devices that can communicate; return 0 if no edge is usable. Adjacent devices with the same frequency are also valid.
Input
The first line contains n, the second line contains n frequencies, followed by n−1 lines of 1-based undirected edges. The original raw text gives no upper bound on the number of nodes (the 100,000 in the catalog was added during compilation); this site specifies 1≤n≤100000, the input is a valid tree, and frequencies are 1, 2, or 3.
Output
Output the single integer required by the problem.
Example 1
Input:
4
1 3 2 1
1 2
2 3
3 4
Output:
2
Example 2
Input:
1
2
Output:
0
Example 3
Input:
3
1 1 1
1 2
2 3
Output:
2
Example notes
The answers to the three public examples are, in order: 2; 0; 2. The examples were checked by independent enumeration, state search, or direct simulation.
Editorial
Loading solution…