warshall's algorithm

[tags] C++
// created by _yun on 2016.4.27

用warshall’s算法计算传递闭包

(1)时间复杂度为:O(n*n*n)
(2)用R的无穷闭包时间复杂度为O(n*n*n*(n - 1))

BinaryRelation BinaryRelation::transitiveClosure() const {
  BooleanMatrix temp(matrix);
  for (int i = 1; i <= temp.getRow(); i++)
    for (int j = 1; j <= temp.getColums(); j++)
      for (int k = 1; k <= temp.getRow(); k++)
        temp.replace(temp.getElement(j, k)|temp.getElement(j, i)&temp.getElement(i, k), j, k);
  BinaryRelation _relation(temp, set);
  return _relation;
}

对称闭包等于原闭包与其逆的 |

BinaryRelation BinaryRelation::symmetricClosure() const {
  BooleanMatrix temp(matrix.getBooleanMatrix()|matrix);
  BinaryRelation _brelation(temp, set);
  return _brelation;
}

自反闭包等于其与对角闭包的 |

BinaryRelation BinaryRelation::reflexiveClosure() const {
  BooleanMatrix temp(matrix);
  for (int i = 1; i <= matrix.getRow(); i++)
      if (matrix.getElement(i, i) == 0) temp.replace(1, i, i);
  BinaryRelation _relation(temp, set);
  return _relation;
}

得到集合中某个元素所在的位置


int BinaryRelation::getSetElePos(int element) {
  for (int i = 1; i <= set.getSize(); i++)
    if (set.get(i) == element) return i;
  return -1;
}

某个元素的入度inDegree

int BinaryRelation::inDegree(int element) {
  if (set.isInSet(element)) {
    int position = getSetElePos(element);
    int result = 0;
    for (int i = 1; i <= matrix.getRow(); i++)
      result += matrix.getElement(i, position);
    return result;
  }
  return -1;
}

某个元素的出度:outDegree

int BinaryRelation::outDegree(int element) {
  if (set.isInSet(element)) {
    int position = getSetElePos(element);
    int result = 0;
    for (int i = 1; i <= matrix.getColums(); i++)
      result += matrix.getElement(position, i);
    return result;
  }
  return -1;
}

关系relation的各种性质:(实现的难度较小)

    // Properties of Relations.
    bool isReflexive() const;
    bool isIrreflexive() const;
    bool isSymmetric() const;
    bool isAsymmetric() const;
    bool isAntisymmetric() const;
    bool isTransitive() const;

    bool isEquivalence() const;

用算法解决实际问题,离散数学中的问题,整个的思路很清晰,但是实现起来并没有想象中那么简单

你可能感兴趣的:(C++)