[LeetCode] Remove Methods From Project

3310. Remove Methods From Project

You are maintaining a project that has n methods numbered from 0 to n - 1.

You are given two integers n and k, and a 2D integer array invocations, where invocations[i] = [ai, bi] indicates that method ai invokes method bi.

There is a known bug in method k. Method k, along with any method invoked by it, either directly or indirectly, are considered suspicious and we aim to remove them.

A group of methods can only be removed if no method outside the group invokes any methods within it.

Return an array containing all the remaining methods after removing all the suspicious methods. You may return the answer in any order. If it is not possible to remove all the suspicious methods, none should be removed.

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

class Solution {
int uf[101010];
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] = min(pu,pv);
}
public:
vector<int> remainingMethods(int n, int k, vector<vector<int>>& methodsRelationship) {
iota(begin(uf),end(uf),0);
vector<vector<int>> adj(n);
for(auto& e : methodsRelationship) {
int u = e[0], v = e[1];
uni(u,v);
adj[u].push_back(v);
}
vector<bool> fl(n);
queue<int> q;
q.push(k); fl[k] = true;
while(q.size()) {
int u = q.front(); q.pop();
for(auto& v : adj[u]) {
if(fl[v]) continue;
fl[v] = true;
q.push(v);
}
}
unordered_map<int, int> gc, flc;
for(int i = 0; i < n; i++) {
int r = find(i);
gc[r]++;
flc[r] += fl[i];
}
vector<int> res;
for(int i = 0; i < n; i++) {
int r = find(i);
if(gc[r] == flc[r]) continue;
res.push_back(i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/10/06/PS/LeetCode/remove-methods-from-project/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.