Ai
1 Star 0 Fork 0

一子二木生三火/算法学习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
leet765.cpp 778 Bytes
一键复制 编辑 原始数据 按行查看 历史
一子二木生三火 提交于 2024-01-22 20:58 +08:00 . 情侣牵手(并查集)
class Solution {
public:
vector<int> father;
int sets;
void build(int n)
{
for (int i = 0; i < n; i++)
{
father.push_back(i);
}
sets = n;
}
int find(int n)
{
if (n != father[n])
father[n] = find(father[n]);
return father[n];
}
void union_(int x, int y)
{
int fx = find(x), fy = find(y);
if (fx != fy)
{
father[fx] = fy;
sets--;
}
}
int minSwapsCouples(vector<int>& row) {
int rown = row.size();
build(rown / 2);
int res = 0;
for (int i = 0; i < rown; i += 2)
union_(row[i] / 2, row[i + 1] / 2);
res = rown / 2 - sets;
return res;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/li-yishenset/algorithm-studying.git
git@gitee.com:li-yishenset/algorithm-studying.git
li-yishenset
algorithm-studying
算法学习
master

搜索帮助