美文网首页
2019-07-17 并查集

2019-07-17 并查集

作者: DreamNeverDie | 来源:发表于2019-07-17 16:55 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    // 并查集
    class UnionFind {
        constructor(n) {
            this.parent = new Array(n);
            this.count = n;
            this.rank = new Array(n);
            for (let i = 0; i < n; i++) {
                this.parent[i] = i;
                this.rank[i] = 1;
            }
        }

        find(p) {
            if (p < 0 || p >= this.count) return;
            let stack = [],
                cur = p,
                prev;
            // path compression 1
            // while (p !== this.parent[p]) {
            //     this.parent[p] = this.parent[this.parent[p]];
            //     p = this.parent(p);
            // }
            // return p
            // path compression 2
            // if (p !== this.parent[p]) {
            //     this.parent[p] = this.find(this.parent[p])
            // }
            while (cur !== this.parent[cur]) {
                stack.push(cur);
                cur = this.parent[cur]
            }
            while (stack.length) {
                this.parent[stack.pop()] = cur
            }
            return this.parent[p];
        }

        isConnected(p, q) {
            return this.find(p) === this.find(q)
        }

        unionElements(p, q) {
            let pId = this.find(p),
                qId = this.find(q);
            if (pId === qId) return;
            if (this.rank[pId] < this.rank[qId]) {
                this.parent[pId] = qId;
            } else if (this.rank[qId] < this.rank[pId]) {
                this.parent[qId] = pId;
            } else {
                this.parent[pId] = qId;
                this.rank[qId]++;
            }
        }
    }
</script>
</body>
</html>

相关文章

  • 2019-07-17 并查集

  • markdown学习

    #并查集 ##并查集的定义 ##并查集的操作

  • 算法模板(四)并查集

    并查集 路径压缩并查集

  • 并查集入门使用

    本文参考自《算法笔记》并查集篇 并查集的定义 什么是并查集?并查集可以理解为是一种维护数据集合的结构。名字中并查集...

  • 并查集练习

    并查集 参考《算法笔记》 三要素:并,查,集。 并差集与一个算法有关,kruskal算法,就可通过并查集实现。 1...

  • 并查集

    并查集 并查集是什么 并查集是一种用来管理元素分组情况的数据结构,并查集可以高效地进行如下操作: 查询元素a和元素...

  • 数据结构与算法(十二)并查集(Union Find)

    本文主要包括以下内容: 并查集的概念 并查集的操作 并查集的实现和优化Quick FindQuick Union基...

  • 并查集

    并查集是什么 并查集是一种用来管理元素分组情况的数据结构。并查集可以高效地进行如下操作。不过需要注意并查集虽然可以...

  • 并查集

    开始时让每个元素构成一个个单元素集合(注意初始化时应使每个元素各成一组)按照一定顺序将属于同一组元素所在的集合合并...

  • 并查集

网友评论

      本文标题:2019-07-17 并查集

      本文链接:https://www.haomeiwen.com/subject/yllclctx.html