- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 33 lines of C++ from the credited upstream file 3336.cpp.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int subsequencePairCount(vector<int>& nums) {4 const int maxNum = ranges::max(nums);5 vector<vector<vector<int>>> mem(6 nums.size(),7 vector<vector<int>>(maxNum + 1, vector<int>(maxNum + 1, -1)));8 return subsequencePairCount(nums, 0, 0, 0, mem);9 }10 11 private:12 static constexpr int kMod = 1'000'000'007;13 14 15 16 int subsequencePairCount(const vector<int>& nums, int i, int x, int y,17 vector<vector<vector<int>>>& mem) {18 if (i == nums.size())19 return x > 0 && x == y;20 if (mem[i][x][y] != -1)21 return mem[i][x][y];22 23 const int skip = subsequencePairCount(nums, i + 1, x, y, mem);24 25 const int take1 =26 subsequencePairCount(nums, i + 1, gcd(x, nums[i]), y, mem);27 28 const int take2 =29 subsequencePairCount(nums, i + 1, x, gcd(y, nums[i]), mem);30 return mem[i][x][y] = (static_cast<long>(skip) + take1 + take2) % kMod;31 }32};33