当前位置:网站首页>365天挑战LeetCode1000题——Day 044 按公因数计算最大组件大小 并查集
365天挑战LeetCode1000题——Day 044 按公因数计算最大组件大小 并查集
2022-07-30 20:00:00 【ShowM3TheCode】
952. 按公因数计算最大组件大小

代码实现(部分看题解)
这题我想两两求公因数,但是不行,很奇怪,反而是答案看上去笨笨的枚举可以。
class DisjointSet {
private:
std::vector<int> parent;
std::vector<int> rank; // 秩
int maxSetNum;
public:
DisjointSet(int max_size) : parent(std::vector<int>(max_size)), rank(std::vector<int>(max_size, 1)), maxSetNum(1) {
for (int i = 0; i < max_size; ++i) parent[i] = i;
}
int find(int x) {
return x == parent[x] ? x : (parent[x] = find(parent[x]));
}
void _union(int x1, int x2) {
int f1 = find(x1);
int f2 = find(x2);
if (f1 == f2) return;
if (rank[f1] > rank[f2]) {
parent[f2] = f1;
rank[f1] += rank[f2];
maxSetNum = max(maxSetNum, rank[f1]);
}
else {
parent[f1] = f2;
rank[f2] += rank[f1];
maxSetNum = max(maxSetNum, rank[f2]);
}
}
bool is_same(int e1, int e2) {
return find(e1) == find(e2);
}
int getHighestRank() {
return maxSetNum;
}
};
class Solution {
public:
int largestComponentSize(vector<int>& nums) {
int n = *max_element(nums.begin(), nums.end());
DisjointSet ds(n + 1);
for (int num : nums) {
for (int j = 2; j * j <= num; j++) {
if (num % j == 0) {
ds._union(num, num / j);
ds._union(num, j);
}
}
}
vector<int> counts(n + 1);
int root = 0, ans = 0;
for (int num : nums) {
root = ds.find(num);
counts[root]++;
ans = max(ans, counts[root]);
}
return ans;
}
};
边栏推荐
猜你喜欢
随机推荐
【Node实现数据加密】
推荐系统-排序层-模型(一):Embedding + MLP(多层感知机)模型【Deep Crossing模型:经典的Embedding+MLP模型结构】
[flink] Error finishing Could not instantiate the executor. Make sure a planner module is on the classpath
Snowflake vs. Redshift的2022战报:两个数据平台谁更适合你?
推荐系统-排序层:排序层架构【用户、物品特征处理步骤】
【请教】SQL语句按列1去重来计算列2之和?
18.客户端会话技术Cookie
Centos7 install mysql8
Mapped Statements collection does not contain value for的解决方法
MySQL分组后取最大一条数据【最优解】
HCIP --- 企业网的三层架构
Interviewer Ali: Describe to me the phenomenon of cache breakdown, and talk about your solution?
el-input can only input integers (including positive numbers, negative numbers, 0) or only integers (including positive numbers, negative numbers, 0) and decimals
MySQL复制表结构、表数据的方法
用jOOQ 3.17投射类型安全的嵌套表记录
MySql密码
Trial writing C language sanbang
linux下mysql8安装
HarmonyOS笔记-----------(三)
“数字化重构系统,搞定 CEO 是第一步”








