Files
reachability-algorithms/algorithm/decremental_scc.h
2022-08-08 22:22:52 +03:00

95 lines
2.0 KiB
C++

#ifndef DECREMENTAL_SCC_H_
#define DECREMENTAL_SCC_H_
#include "algorithm/roditty_zwick.h"
#include "algorithm/tarjan.h"
#include "tree/breadth_first_tree.h"
using namespace graph;
using namespace tree;
namespace algo {
template<typename T>
class DecrementalSCC : public RodittyZwick<T> {
public:
DecrementalSCC(Digraph<T> G) : G(G) {}
void init();
void findSCC();
bool query(const T& u, const T& v);
void remove(const T& u, const T& v);
private:
Digraph<T> G;
// Array used to answer strong connectivity queries in O(1) time
std::map<T, T> A;
// Maintain in-out bfs trees
std::map<T, BreadthFirstTree<T>> inTree;
std::map<T, BreadthFirstTree<T>> outTree;
// Connect each representative with its SCC
std::map<T, SCC<T>> connection;
};
template<typename T>
void DecrementalSCC<T>::init() {
findSCC();
}
template<typename T>
void DecrementalSCC<T>::findSCC() {
auto SCCs = Tarjan<T>(G).execute();
for (auto& C : SCCs) {
const auto& w = C.representative();
for (const auto& v : C.adjMatrix)
A[v.first] = w;
outTree[w] =
BreadthFirstTree<T>(BreadthFirstSearch<T>(C).execute(w));
inTree[w] =
BreadthFirstTree<T>(BreadthFirstSearch<T>(C.reverse()).execute(w));
connection[w] = C;
}
}
template<typename T>
bool DecrementalSCC<T>::query(const T& u, const T& v) {
return A[u] == A[v];
}
template<typename T>
void DecrementalSCC<T>::remove(const T& u, const T& v) {
G.adjMatrix[u].erase(v);
// If u and v are not in the same SCC, do nothing
if (A[u] != A[v]) return;
const auto& w = A[u];
connection[w].remove(u, v);
// Update In(w) and Out(w) if they contain the edge
if (inTree[w].contains(u, v) || outTree[w].contains(u, v)) {
auto C = connection[w];
inTree[w] =
BreadthFirstTree<T>(BreadthFirstSearch<T>(C.reverse()).execute(w));
outTree[w] =
BreadthFirstTree<T>(BreadthFirstSearch<T>(C).execute(w));
}
// If a SCC is broken, compute all SCCs again
if (!inTree[w].contains(u) || !outTree[w].contains(v)) {
findSCC();
}
}
}; // namespace algo
#endif