[LeetCode] Number of Good Paths

2421. Number of Good Paths

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:

  1. The starting node and the ending node have the same value.
  2. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
vector<int> uf;
unordered_map<int, int> level;
unordered_map<int, int> par;
unordered_map<int, vector<int>> adj;
void dfs(int u, int p, int lvl = 0) {
par[u] = p;
level[u] = lvl;
for(auto v : adj[u]) {
if(v == p) continue;
dfs(v,u, lvl + 1);
}
}
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu] = uf[pv] = level[pu] < level[pv] ? pu : pv;
}
public:
int numberOfGoodPaths(vector<int>& vals, vector<vector<int>>& edges) {
for(auto e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0,-1);
vector<pair<int, int>> A;
for(int i = 0; i < vals.size(); i++) A.push_back({vals[i],i});
uf = vector<int>(vals.size());
iota(begin(uf), end(uf),0);
int res = vals.size();
sort(begin(A), end(A));
int l = 0, r = 0, n = A.size();
while(r < n) {
while(r < n and A[l].first == A[r].first) r++;
unordered_map<int, int> now;
while(l < r) {
auto [_, u] = A[l];
u = find(u);
while(par[u] != -1 and vals[par[u]] <= A[l].first) {
uni(u,par[u]);
u = find(u);
}
res += now[u];
now[u] += 1;
l += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/10/PS/LeetCode/number-of-good-paths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.