Problem 940
Number of Good Paths
Hard · 30 pts · Tree, Graph, Union Find, Sorting
Problem
A tree has N nodes numbered from 1, and node i has value VALS[i]. A good path is a simple path whose two end nodes have the same value and whose other nodes all have values not greater than that. A single node is a good path, and a path and its reverse count once. Count the good paths. Process nodes by increasing value, joining each to neighbours that are not larger with union-find; then nodes of the current value that share a component can pair up.
Input
The first line contains N. The second line contains the N values. Each of the next N - 1 lines contains an edge u v.
Output
Print the number of good paths.
Constraints
1 <= N <= 30000; 0 <= VALS[i] <= 10^5; the edges form a tree
Example input
5 1 3 2 1 3 1 2 1 3 3 4 3 5
Example output
6
Explanation
With values 1 3 2 1 3 and edges 1-2, 1-3, 3-4, 3-5, the five single nodes are good paths, and so is 2-1-3-5 (ends both 3, middle values 1 and 2). That makes 6 good paths.