Add contains method for single vertex and hash function for SCCs

This commit is contained in:
stefiosif
2023-02-10 18:20:00 +02:00
parent 54eee41f7d
commit 2175ac0ca9
3 changed files with 47 additions and 25 deletions

View File

@@ -24,6 +24,12 @@ public:
// Reverse graph directions
auto reverse();
//
auto contains(const T& u);
friend std::ostream& operator<<<>(std::ostream& os, Digraph<T>& G);
};
template<typename T>
@@ -60,6 +66,26 @@ auto Digraph<T>::reverse() {
return revMatrix;
}
template<typename T>
auto Digraph<T>::contains(const T& u) {
return this->adjList.count(u);
}
template<typename T>
std::ostream& operator<<(std::ostream& os, Digraph<T>& G) {
os << "V: " << G.V() << " E: " << G.E() << '\n';
for (const auto& u : G.vertices()) {
if (!G.adjList[u].empty()) {
for (const auto& v : G.adjList[u]) {
os << u << "->" << v << ' ';
}
os << '\n';
}
}
os << '\n';
return os;
}
} // namespace graph
#endif

View File

@@ -27,7 +27,7 @@ public:
virtual void remove(const T& u, const T& v) =0;
// Return graph vertices
auto vertices();
auto vertices() const;
// Return num. of vertices
std::uint16_t V();
@@ -38,11 +38,10 @@ public:
// Adjacency matrix representation
std::unordered_map<T, std::unordered_set<T>> adjList;
friend std::ostream& operator<<<>(std::ostream& os, Graph<T>& G);
};
template<typename T>
auto Graph<T>::vertices() {
auto Graph<T>::vertices() const{
return std::views::keys(adjList);
}
@@ -60,20 +59,7 @@ std::uint16_t Graph<T>::E() {
return edges;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, Graph<T>& G) {
os << "V: " << G.V() << " E: " << G.E() << '\n';
for (const auto& u : this->vertices()) {
if (!this->adjList[u].empty()) {
for (const auto& v : this->adjList[u]) {
os << u << "->" << v << ' ';
}
os << '\n';
}
}
os << '\n';
return os;
}
} // namespace graph

View File

@@ -18,11 +18,14 @@ public:
SCC(Digraph<T> G, T id) : id(id) { normalize(); }
// Return true if v is part of this SCC
bool member(const T& v);
// Return true if u is part of this SCC
bool contains(const T& u) const;
// Representative vertex of this SCC
T id;
T id{};
//
std::unordered_map<T, std::unordered_set<T>> neighboorList;
bool operator==(const SCC& o) const;
private:
@@ -34,18 +37,18 @@ template<typename T>
void SCC<T>::normalize() {
for (const auto& u : this->vertices()) {
for (const auto& v : this->adjList[u]) {
if (!this->adjList.count(v)) {
if (!this->contains(v)) {
this->adjList[u].erase(v);
this->adjList.erase(v);
neighboorList[u].insert(v);
}
}
}
}
template<typename T>
bool SCC<T>::member(const T& v) {
const auto& V = this->vertices();
return std::find(V.begin(), V.end(), v) != V.end();
bool SCC<T>::contains(const T& u) const {
return this->adjList.count(u);
}
template<typename T>
@@ -53,6 +56,13 @@ bool SCC<T>::operator==(const SCC& o) const{
return id == o.id;
}
template<typename T>
struct HashSCC {
std::size_t operator()(const SCC<T>& C) const {
return static_cast<std::size_t>(C.id);
}
};
}; // namespace graph
#endif