Skip to content

Commit ff7389d

Browse files
authored
Create 2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups.cpp
1 parent 9524c51 commit ff7389d

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
class Solution {
2+
int Father[505];
3+
int FindFather(int x)
4+
{
5+
if (Father[x]!=x)
6+
Father[x] = FindFather(Father[x]);
7+
return Father[x];
8+
}
9+
10+
void Union(int x, int y)
11+
{
12+
x = Father[x];
13+
y = Father[y];
14+
if (x<y) Father[y] = x;
15+
else Father[x] = y;
16+
}
17+
18+
vector<int>next[505];
19+
20+
public:
21+
int magnificentSets(int n, vector<vector<int>>& edges)
22+
{
23+
for (int i=1; i<=n; i++)
24+
Father[i] = i;
25+
for (auto edge: edges)
26+
{
27+
int a = edge[0], b = edge[1];
28+
if (FindFather(a)!=FindFather(b))
29+
Union(a,b);
30+
next[a].push_back(b);
31+
next[b].push_back(a);
32+
}
33+
34+
unordered_map<int,vector<int>>groups;
35+
for (int i=1; i<=n; i++)
36+
groups[FindFather(i)].push_back(i);
37+
38+
int ret = 0;
39+
40+
for (auto& [_, nodes]: groups)
41+
{
42+
int ans = 0;
43+
for (int start: nodes)
44+
{
45+
unordered_map<int,int>level;
46+
level[start] = 1;
47+
queue<pair<int,int>>q;
48+
q.push({start, 1});
49+
50+
while (!q.empty())
51+
{
52+
auto [cur, d] = q.front();
53+
q.pop();
54+
ans = max(ans, d);
55+
56+
for (int nxt: next[cur])
57+
{
58+
if (level.find(nxt)==level.end())
59+
{
60+
level[nxt] = d+1;
61+
q.push({nxt, d+1});
62+
}
63+
else if (level[nxt] == d)
64+
return -1;
65+
}
66+
}
67+
}
68+
ret += ans;
69+
}
70+
71+
return ret;
72+
}
73+
};

0 commit comments

Comments
 (0)