-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind All People With Secret.cpp
140 lines (119 loc) · 2.94 KB
/
Find All People With Secret.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// sample 319 ms submission
static const int _ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }();
class UnionFindSet
{
public:
UnionFindSet(int n) : _parent(n), _size(n)
{
for(int i = 0; i < n; ++i)
{
_parent[i] = i;
_size[i] = 1;
}
}
bool Union(int x, int y)
{
int rootX = Find(x);
int rootY = Find(y);
if(rootX == rootY)
{
return true;
}
if(rootX != rootY)
{
if(_size[rootY] < _size[rootX])
{
_parent[rootY] = rootX;
_size[rootX] += _size[rootY];
}
else
{
_parent[rootX] = rootY;
_size[rootY] += _size[rootX];
}
}
return false;
}
int Find(int x)
{
if(_parent[x] == x)
{
return x;
}
return _parent[x] = Find(_parent[x]);
}
int getGroup()
{
int g = 0;
for(int i = 0; i < _parent.size(); ++i)
{
if(i == _parent[i])
{
++g;
}
}
return g;
}
vector<int> getGroupVec()
{
vector<int> res;
for(int i = 0; i < _parent.size(); ++i)
{
if(_parent[0] == _parent[i])
{
res.emplace_back(i);
}
}
return res;
}
void set(int num)
{
//cout << num << endl;
_parent[num] = num;
_size[num] = 1;
}
private:
vector<int> _parent;
vector<int> _size;
};
class Solution
{
public:
vector<int> findAllPeople(int n, vector<vector<int>> &meetings, int firstPerson)
{
sort(meetings.begin(), meetings.end(), [&](vector<int> &a, vector<int> &b)
{
return a[2] < b[2];
});
//for(auto& meet : meetings){
// cout << meet[0] << " " << meet[1] << " " << meet[2] << endl;
//}
vector<int> res(1, 0);
UnionFindSet ufs(n);
ufs.Union(0, firstPerson);
int m = meetings.size();
for(int i = 0; i < m; ++i)
{
int time = meetings[i][2];
ufs.Union(meetings[i][0], meetings[i][1]);
if(i == m - 1 || meetings[i][2] != meetings[i + 1][2])
{
int j = i;
while(j >= 0 && meetings[j][2] == time)
{
if(ufs.Find(meetings[j][1]) != ufs.Find(0))
{
ufs.set(meetings[j][1]);
}
if(ufs.Find(meetings[j][0]) != ufs.Find(0))
{
ufs.set(meetings[j][0]);
}
--j;
}
}
}
//cout << "------------" << endl;
return ufs.getGroupVec();
}
};