|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int magnificentSets(int n, vector<vector<int>>& edges) { |
| 4 | + vector<vector<int>> adj(n + 1); |
| 5 | + for (auto& edge : edges) { |
| 6 | + adj[edge[0]].push_back(edge[1]); |
| 7 | + adj[edge[1]].push_back(edge[0]); |
| 8 | + } |
| 9 | + |
| 10 | + vector<int> color(n + 1, 0); |
| 11 | + vector<vector<int>> components; |
| 12 | + |
| 13 | + function<bool(int, vector<int>&)> bfs = [&](int start, vector<int>& component) { |
| 14 | + queue<int> q; |
| 15 | + q.push(start); |
| 16 | + color[start] = 1; |
| 17 | + component.push_back(start); |
| 18 | + |
| 19 | + while (!q.empty()) { |
| 20 | + int node = q.front(); |
| 21 | + q.pop(); |
| 22 | + |
| 23 | + for (int neighbor : adj[node]) { |
| 24 | + if (color[neighbor] == 0) { |
| 25 | + color[neighbor] = -color[node]; |
| 26 | + q.push(neighbor); |
| 27 | + component.push_back(neighbor); |
| 28 | + } else if (color[neighbor] == color[node]) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + return true; |
| 34 | + }; |
| 35 | + |
| 36 | + for (int i = 1; i <= n; i++) { |
| 37 | + if (color[i] == 0) { |
| 38 | + vector<int> component; |
| 39 | + if (!bfs(i, component)) { |
| 40 | + return -1; |
| 41 | + } |
| 42 | + components.push_back(component); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + int maxGroups = 0; |
| 47 | + |
| 48 | + auto getMaxDepth = [&](int start) { |
| 49 | + queue<int> q; |
| 50 | + unordered_map<int, int> dist; |
| 51 | + q.push(start); |
| 52 | + dist[start] = 1; |
| 53 | + int maxDepth = 1; |
| 54 | + |
| 55 | + while (!q.empty()) { |
| 56 | + int node = q.front(); |
| 57 | + q.pop(); |
| 58 | + |
| 59 | + for (int neighbor : adj[node]) { |
| 60 | + if (!dist.count(neighbor)) { |
| 61 | + dist[neighbor] = dist[node] + 1; |
| 62 | + q.push(neighbor); |
| 63 | + maxDepth = max(maxDepth, dist[neighbor]); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return maxDepth; |
| 68 | + }; |
| 69 | + |
| 70 | + for (auto& component : components) { |
| 71 | + int localMax = 0; |
| 72 | + for (int node : component) { |
| 73 | + localMax = max(localMax, getMaxDepth(node)); |
| 74 | + } |
| 75 | + maxGroups += localMax; |
| 76 | + } |
| 77 | + |
| 78 | + return maxGroups; |
| 79 | + } |
| 80 | +}; |
| 81 | + |
| 82 | +int Main() { |
| 83 | + Solution sol; |
| 84 | + vector<vector<int>> edges1 = {{1,2},{1,4},{1,5},{2,6},{2,3},{4,6}}; |
| 85 | + cout << sol.magnificentSets(6, edges1) << endl; |
| 86 | + |
| 87 | + vector<vector<int>> edges2 = {{1,2},{2,3},{3,1}}; |
| 88 | + cout << sol.magnificentSets(3, edges2) << endl; |
| 89 | + |
| 90 | + return 0; |
| 91 | +} |
0 commit comments