104 lines
2.5 KiB
C++
104 lines
2.5 KiB
C++
#ifndef RODITTY_ZWICK_SCC_H_
|
|
#define RODITTY_ZWICK_SCC_H_
|
|
|
|
#include "algorithm/decremental_reachability.h"
|
|
#include "algorithm/tarjan.h"
|
|
#include "graph/breadth_first_tree.h"
|
|
|
|
namespace algo {
|
|
|
|
template<typename T>
|
|
class RodittyZwick : public DecrementalReachability<T> {
|
|
public:
|
|
RodittyZwick() = default;
|
|
|
|
explicit RodittyZwick(graph::Digraph<T> G) { this->G = G; }
|
|
|
|
//
|
|
void init() override;
|
|
|
|
//
|
|
void findSCC(graph::Digraph<T> G);
|
|
|
|
// Return true if u and v are in the same SCC
|
|
bool query(const T& u, const T& v) override;
|
|
|
|
// Delete collection of edges
|
|
void remove(const std::vector<std::pair<T, T>>& edges) override;
|
|
|
|
// Remove edge (u,v) and update A accordingly for fast checking query
|
|
void remove(const T& u, const T& v);
|
|
|
|
std::unordered_map<T, SCC<T>> getComponentMap() { return C; }
|
|
private:
|
|
// Array used to answer strong connectivity queries in O(1) time
|
|
std::unordered_map<T, T> A;
|
|
|
|
// Connect each representative with its SCC
|
|
std::unordered_map<T, SCC<T>> C;
|
|
|
|
// Maintain in-out bfs trees
|
|
std::unordered_map<T, BreadthFirstTree<T>> In;
|
|
std::unordered_map<T, BreadthFirstTree<T>> Out;
|
|
};
|
|
|
|
template<typename T>
|
|
void RodittyZwick<T>::init() {
|
|
findSCC(this->G);
|
|
}
|
|
|
|
template<typename T>
|
|
void RodittyZwick<T>::findSCC(graph::Digraph<T> G) {
|
|
auto SCCs = Tarjan<T>(G.adjList).execute();
|
|
|
|
for (auto& c : SCCs) {
|
|
const auto& w = c.id;
|
|
|
|
for (const auto& v : c.vertices())
|
|
A[v] = w;
|
|
|
|
Out[w] = BreadthFirstTree<T>(c, w);
|
|
In[w] = BreadthFirstTree<T>(c.reverse(), w);
|
|
|
|
C[w] = c;
|
|
}
|
|
}
|
|
|
|
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 std::vector<std::pair<T, T>>& edges) {
|
|
for (const auto& [u, v] : edges)
|
|
remove(u, 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 TODO:remove useless comments
|
|
// is this not better if i utilize A matrix, since we are going traversing between components.. ? TODO
|
|
if (!In[w].adjList[u].contains(v) && !Out[w].adjList[u].contains(v))
|
|
return;
|
|
|
|
// Update In(w) and Out(w)
|
|
Out[w] = BreadthFirstTree<T>(C[w], w);
|
|
In[w] = BreadthFirstTree<T>(C[w].reverse(), w);
|
|
|
|
// If a SCC is broken, compute the new SCCs
|
|
if (!In[w].contains(u) || !Out[w].contains(v))
|
|
findSCC(C[w]);
|
|
}
|
|
|
|
}; // namespace algo
|
|
|
|
#endif |