Files
reachability-algorithms/algorithm/roditty_zwick.h

101 lines
2.2 KiB
C++

#ifndef RODITTY_ZWICK_H_
#define RODITTY_ZWICK_H_
#include "algorithm/decremental_reachability.h"
#include "algorithm/tarjan.h"
#include "graph/breadth_first_tree.h"
using namespace graph;
namespace algo {
template<typename T>
class RodittyZwick : public DecrementalReachability<T> {
public:
RodittyZwick() = default;
RodittyZwick(Digraph<T> G) { this->G = G; }
//
void init() override;
//
void findSCC();
// Return true if u and v are in the same SCC
bool query(const T& u, const T& v) override;
// Remove edge (u,v) and update A accordingly for fast checking query
void remove(const T& u, const T& v) override;
void setGraph(Digraph<T> G);
private:
// Array used to answer strong connectivity queries in O(1) time
std::map<T, T> A;
// Connect each representative with its SCC
std::map<T, SCC<T>> C;
// Maintain in-out bfs trees
std::map<T, BreadthFirstTree<T>> inTree;
std::map<T, BreadthFirstTree<T>> outTree;
};
template<typename T>
void RodittyZwick<T>::init() {
findSCC();
}
template<typename T>
void RodittyZwick<T>::findSCC() {
auto SCCs = Tarjan<T>(this->G.adjMatrix).execute();
for (auto& SCC : SCCs) {
const auto& w = SCC.id;
for (const auto& v : std::views::keys(SCC.adjMatrix))
A[v] = w;
outTree[w] = BreadthFirstTree<T>(SCC, w);
inTree[w] = BreadthFirstTree<T>(SCC.reverse(), w);
C[w] = SCC;
}
}
template<typename T>
bool RodittyZwick<T>::query(const T& u, const T& v) {
return A[u] == A[v];
}
template<typename T>
void RodittyZwick<T>::remove(const T& u, const T& v) {
const auto& w = A[u];
C[w].remove(u, v);
this->G.remove(u, v);
// If u and v are not in the same SCC, do nothing
if (A[u] != A[v]) return;
// If edge (u,v) is not contained in both inTree and outTree do nothing
if (!inTree[w].adjMatrix[u].contains(v) &&
!outTree[w].adjMatrix[u].contains(v))
return;
// Update In(w) and Out(w)
outTree[w] = BreadthFirstTree<T>(C[w], w);
inTree[w] = BreadthFirstTree<T>(C[w].reverse(), w);
// If a SCC is broken, compute all SCCs again
if (!inTree[w].adjMatrix.count(u) || !outTree[w].adjMatrix.count(v))
findSCC();
}
template<typename T>
void RodittyZwick<T>::setGraph(Digraph<T> G) {
this->G = G;
}
}; // namespace algo
#endif