-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathDirectedCycle.h
71 lines (59 loc) · 1.81 KB
/
DirectedCycle.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifndef ALGS4_DIRECTEDCYCLE_H
#define ALGS4_DIRECTEDCYCLE_H
#include <list>
#include <optional>
#include <type_traits>
#include <vector>
#include "DirectedEdge.h"
#include "GraphBase.h"
template<typename T>
class DirectedCycle {
private:
std::vector<bool> marked;
std::vector<std::optional<T> > edgeTo;
std::list<T> cycle_;
std::vector<bool> onStack; // vertices on recursive call stack
void dfs(const GraphBase<T> &G, int v);
public:
explicit DirectedCycle(const GraphBase<T> &G);
bool hasCycle() const { return !cycle_.empty(); }
std::list<T> cycle() const { return cycle_; }
};
template<typename T>
void DirectedCycle<T>::dfs(const GraphBase<T> &G, int v) {
onStack[v] = true;
marked[v] = true;
for (const auto &e: G.adj(v)) {
int w;
if constexpr (std::is_same_v<std::decay_t<decltype(e)>, DirectedEdge>) w = e.to();
else w = e;
if (hasCycle()) {
return;
} else if (!marked[w]) {
edgeTo[w] = e;
dfs(G, w);
} else if (onStack[w]) {
if constexpr (std::is_same_v<std::decay_t<decltype(e)>, DirectedEdge>) {
auto x = e;
for (; x.from() != w; x = *edgeTo[x.from()]) {
cycle_.push_front(x);
}
cycle_.push_front(x);
} else {
for (int x = v; x != w; x = *edgeTo[x]) {
cycle_.push_front(x);
}
cycle_.push_front(w);
cycle_.push_front(v);
}
}
}
onStack[v] = false;
}
template<typename T>
DirectedCycle<T>::DirectedCycle(const GraphBase<T> &G) : marked(G.V()), edgeTo(G.V()), onStack(G.V()) {
for (int v = 0; v < G.V(); ++v) {
if (!marked[v]) dfs(G, v);
}
}
#endif //ALGS4_DIRECTEDCYCLE_H