并查集模板+二进制中1的位数mask
int FindFather(vector<int>& nums, int father) { if (father == nums[father]) return father; return nums[father] = FindFather(nums, nums[father]); } void Init(vector<int>& nums, int n) { for (int i = 0; i < n; ++i) nums.push_back(i); } void Merge(vector<int>& nums, int x, int y) { int fx = FindFather(nums, x); int fy = FindFather(nums, y); if (fx != fy) nums[fx] = nums[fy]; }
二进制如下则会求出j从最高位开始的所有可能mask
for (int s = j; s > 0; s = (s - 1) & j)
假设j=1101, 则可能的有 1101、1100、1001、1000、101、100、001
浙公网安备 33010602011771号