|
| 1 | +//go:build ignore |
| 2 | +#include "cpp/common/Solution.h" |
| 3 | +#include <algorithm> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | +using json = nlohmann::json; |
| 7 | + |
| 8 | +constexpr int MAX_N = 100000; |
| 9 | +array<vector<int>, MAX_N + 1> PRIMES; |
| 10 | + |
| 11 | +bool inited = false; |
| 12 | +static void init() { |
| 13 | + if (inited) { |
| 14 | + return; |
| 15 | + } |
| 16 | + for (int i = 2; i <= MAX_N; ++i) { |
| 17 | + if (PRIMES[i].empty()) { |
| 18 | + for (int j = i; j <= MAX_N; j += i) { |
| 19 | + PRIMES[j].push_back(i); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +class UnionFind { |
| 26 | + vector<int> fa; |
| 27 | + vector<int> size; |
| 28 | + |
| 29 | +public: |
| 30 | + int cc; |
| 31 | + explicit UnionFind(int n) : fa(n), size(n, 1), cc(n) { |
| 32 | + for (int i = 0; i < n; i++) { |
| 33 | + fa[i] = i; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + int find(int x) { |
| 38 | + if (fa[x] != x) { |
| 39 | + fa[x] = find(fa[x]); |
| 40 | + } |
| 41 | + return fa[x]; |
| 42 | + } |
| 43 | + |
| 44 | + bool merge(int x, int y) { |
| 45 | + int px = find(x), py = find(y); |
| 46 | + if (px == py) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + fa[px] = py; |
| 50 | + size[py] += size[px]; |
| 51 | + cc--; |
| 52 | + return true; |
| 53 | + } |
| 54 | + |
| 55 | + int get_size(int x) { return size[find(x)]; } |
| 56 | +}; |
| 57 | + |
| 58 | +class Solution { |
| 59 | +public: |
| 60 | + int largestComponentSize(const vector<int> &nums) { |
| 61 | + init(); |
| 62 | + int n = nums.size(); |
| 63 | + UnionFind uf(n); |
| 64 | + unordered_map<int, int> primes_idx; |
| 65 | + for (int i = 0; i < n; ++i) { |
| 66 | + for (int p : PRIMES[nums[i]]) { |
| 67 | + auto it = primes_idx.find(p); |
| 68 | + if (it != primes_idx.end()) { |
| 69 | + uf.merge(i, it->second); |
| 70 | + } |
| 71 | + primes_idx[p] = i; |
| 72 | + } |
| 73 | + } |
| 74 | + int ans = 0; |
| 75 | + for (int i = 0; i < n; ++i) { |
| 76 | + ans = max(ans, uf.get_size(i)); |
| 77 | + } |
| 78 | + return ans; |
| 79 | + } |
| 80 | +}; |
| 81 | + |
| 82 | +json leetcode::qubh::Solve(string input_json_values) { |
| 83 | + vector<string> inputArray; |
| 84 | + size_t pos = input_json_values.find('\n'); |
| 85 | + while (pos != string::npos) { |
| 86 | + inputArray.push_back(input_json_values.substr(0, pos)); |
| 87 | + input_json_values = input_json_values.substr(pos + 1); |
| 88 | + pos = input_json_values.find('\n'); |
| 89 | + } |
| 90 | + inputArray.push_back(input_json_values); |
| 91 | + |
| 92 | + Solution solution; |
| 93 | + vector<int> nums = json::parse(inputArray.at(0)); |
| 94 | + return solution.largestComponentSize(nums); |
| 95 | +} |
0 commit comments