There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n
nodes numbered from 0
to n - 1
and exactly n - 1
edges.
You are given a 0-indexed integer array vals
of length n
where vals[i]
denotes the value of the ith
node. You are also given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
A good path is a simple path that satisfies the following conditions:
- The starting node and the ending node have the same value.
- All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
Return the number of distinct good paths.
Note that a path and its reverse are counted as the same path. For example, 0 -> 1
is considered to be the same as 1 -> 0
. A single node is also considered as a valid path.
Example 1:
Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]] Output: 6 Explanation: There are 5 good paths consisting of a single node. There is 1 additional good path: 1 -> 0 -> 2 -> 4. (The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.) Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].
Example 2:
Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]] Output: 7 Explanation: There are 5 good paths consisting of a single node. There are 2 additional good paths: 0 -> 1 and 2 -> 3.
Example 3:
Input: vals = [1], edges = [] Output: 1 Explanation: The tree consists of only one node, so there is one good path.
Constraints:
n == vals.length
1 <= n <= 3 * 104
0 <= vals[i] <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.
class Solution:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
n = len(vals)
p = list(range(n))
size = defaultdict(Counter)
for i, v in enumerate(vals):
size[i][v] = 1
ans = n
for v, a in sorted(zip(vals, range(n))):
for b in g[a]:
if vals[b] > v:
continue
pa, pb = find(a), find(b)
if pa != pb:
ans += size[pa][v] * size[pb][v]
p[pa] = pb
size[pb][v] += size[pa][v]
return ans
class Solution {
private int[] p;
public int numberOfGoodPaths(int[] vals, int[][] edges) {
int n = vals.length;
p = new int[n];
int[][] arr = new int[n][2];
List<Integer>[] g = new List[n];
for (int i = 0; i < n; ++i) {
g[i] = new ArrayList<>();
}
for (int[] e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
Map<Integer, Map<Integer, Integer>> size = new HashMap<>();
for (int i = 0; i < n; ++i) {
p[i] = i;
arr[i] = new int[] {vals[i], i};
size.computeIfAbsent(i, k -> new HashMap<>()).put(vals[i], 1);
}
Arrays.sort(arr, (a, b) -> a[0] - b[0]);
int ans = n;
for (var e : arr) {
int v = e[0], a = e[1];
for (int b : g[a]) {
if (vals[b] > v) {
continue;
}
int pa = find(a), pb = find(b);
if (pa != pb) {
ans += size.get(pa).getOrDefault(v, 0) * size.get(pb).getOrDefault(v, 0);
p[pa] = pb;
size.get(pb).put(v, size.get(pb).getOrDefault(v, 0) + size.get(pa).getOrDefault(v, 0));
}
}
}
return ans;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
class Solution {
public:
int numberOfGoodPaths(vector<int>& vals, vector<vector<int>>& edges) {
int n = vals.size();
vector<int> p(n);
iota(p.begin(), p.end(), 0);
function<int(int)> find;
find = [&](int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
vector<vector<int>> g(n);
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
unordered_map<int, unordered_map<int, int>> size;
vector<pair<int, int>> arr(n);
for (int i = 0; i < n; ++i) {
arr[i] = {vals[i], i};
size[i][vals[i]] = 1;
}
sort(arr.begin(), arr.end());
int ans = n;
for (auto [v, a] : arr) {
for (int b : g[a]) {
if (vals[b] > v) {
continue;
}
int pa = find(a), pb = find(b);
if (pa != pb) {
ans += size[pa][v] * size[pb][v];
p[pa] = pb;
size[pb][v] += size[pa][v];
}
}
}
return ans;
}
};
func numberOfGoodPaths(vals []int, edges [][]int) int {
n := len(vals)
p := make([]int, n)
size := map[int]map[int]int{}
type pair struct{ v, i int }
arr := make([]pair, n)
for i, v := range vals {
p[i] = i
if size[i] == nil {
size[i] = map[int]int{}
}
size[i][v] = 1
arr[i] = pair{v, i}
}
var find func(x int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
sort.Slice(arr, func(i, j int) bool { return arr[i].v < arr[j].v })
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
ans := n
for _, e := range arr {
v, a := e.v, e.i
for _, b := range g[a] {
if vals[b] > v {
continue
}
pa, pb := find(a), find(b)
if pa != pb {
ans += size[pb][v] * size[pa][v]
p[pa] = pb
size[pb][v] += size[pa][v]
}
}
}
return ans
}