class Solution {
private:
vector<int> p;
vector<bool> secret;
void build(int n, int firstPerson) {
p.resize(n);
secret.resize(n);
for (int i = 0; i < n; i++) {
p[i] = i;
secret[i] = false;
}
p[firstPerson] = 0;
secret[0] = true;
}
int find(int i) {
if (i != p[i]) p[i] = find(p[i]);
return p[i];
}
void unionSets(int x, int y) {
int fx = find(x), fy = find(y);
if (fx != fy) {
p[fx] = fy;
secret[fy] = secret[fx] || secret[fy];
}
}
public:
vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) {
build(n, firstPerson);
sort(meetings.begin(), meetings.end(), [](auto& lhs, auto& rhs) {
return lhs[2] < rhs[2];
});
int m = meetings.size();
for (int l = 0, r; l < m; ) {
r = l;
while (r + 1 < m && meetings[l][2] == meetings[r + 1][2]) {
r++;
}
for (int i = l; i <= r; i++) {
unionSets(meetings[i][0], meetings[i][1]);
}
for (int i = l, a, b; i <= r; i++) {
a = meetings[i][0]; b = meetings[i][1];
// reset
if (!secret[find(a)]) p[a] = a;
if (!secret[find(b)]) p[b] = b;
}
l = r + 1;
}
vector<int> res;
for (int i = 0; i < n; i++) {
if (secret[find(i)]) res.emplace_back(i);
}
return res;
}
};