Files
reachability-algorithms/algorithm/italiano.h
2022-09-16 15:17:50 +03:00

107 lines
2.4 KiB
C++

#ifndef ITALIANO_H_
#define ITALIANO_H_
#include "algorithm/roditty_zwick.h"
#include "algorithm/tarjan.h"
#include "graph/breadth_first_tree.h"
#include <forward_list>
using namespace graph;
namespace algo {
template<typename T>
class Italiano : public RodittyZwick<T> {
public:
Italiano(Digraph<T> G) : G(G) {}
void init();
bool query(const T& u, const T& v);
void remove(const T& u, const T& v);
private:
Digraph<T> G;
// Transitive closure matrix, used to answer reachability queries in O(1)
std::map<T, std::map<T, bool>> TC;
// Each vertex's reachability tree
std::map<T, BreadthFirstTree<T>> RT;
// Incoming / Outgoing edges
struct Edges {
std::forward_list<T> inc;
std::forward_list<T> out;
};
std::map<T, Edges> E;
};
template<typename T>
void Italiano<T>::init() {
for (const auto& u : std::views::keys(G.adjMatrix)) {
for (const auto& v : G.adjMatrix[u]) {
E[v].inc.push_front(u);
E[u].out.push_front(v);
TC[u][v] = false;
}
RT[u] = BreadthFirstTree(G, u);
TC[u][u] = true;
for (const auto& v : std::views::keys(RT[u].adjMatrix)) {
TC[u][v] = true;
}
}
}
template<typename T>
bool Italiano<T>::query(const T& u, const T& v) {
return TC[u][v];
}
template<typename T>
void Italiano<T>::remove(const T& u, const T& v) {
std::map<T, std::forward_list<T>> R;
for (const auto& w : std::views::keys(G.adjMatrix)) {
if (RT[w].contains(u, v) &&
std::distance(E[w].inc.begin(), E[w].inc.end()) > 1) {
if (E[v].inc.front() == u) {
E[v].inc.pop_front();
R[w].push_front(E[v].inc.front());
E[v].inc.push_front(u);
} else {
R[w].push_front(E[v].inc.front());
}
}
}
E[u].inc.remove(v);
E[u].out.remove(u);
G.remove(u, v);
for (const auto& w : std::views::keys(G.adjMatrix)) {
bool hooked = false;
// R contains all vertices that need a hook-parent
while (!R[w].empty()) {
// z is a candidate hook-parent if it is in RT[w]
const auto& toHook = R[w].front();
for (const auto& z : E[toHook].inc) {
if (RT[w].contains(u, z)) {
R[w].remove(toHook);
hooked = true;
break;
}
}
if (!hooked) {
TC[w][toHook] = false;
for (const auto& z : E[toHook].out) {
if (RT[w].contains(toHook, z))
R[w].push_front(z);
}
}
}
}
}
} // namespace algo
#endif