Skip to content

union-find, quick-union, weighted-quick-union #5

@barretlee

Description

@barretlee

动态联通性这块的算法还是有点不好理解,下面是效率递增的三个算法:

回到家再继续分析这几个算法;)

function weightedQuickUnion(input, combo) {
  var sz = [];
  for(var i = 0, len = input.length; i < len; i++) {
    sz.push(1);
  }
  for(var i = 0, len = combo.length; i < len; i++) {
    var p = combo[i][0];
    var q = combo[i][1];
    if(root(p) != root(q)) {
      if(sz[p] > sz[q]) {
        sz[p] += sz[q];
        input[q] = p;
      } else {
        sz[q] += sz[p];
        input[p] = q;
      }
    }
  }

  return input;

  function root(n) {
    while(input[n] != n) {
      n = input[n];
    }
    return n;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions