Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tarjan's SCC Algo------------------------------------------------------------------------
- //Finds the earliest node in walk that can be reached by moving forward (lowLink)
- //When we find the node with an index matching this lowLink (root), we emit it and the walk that reached it (SCC)
- //This could be a cycle, or a singleton. The emission order is the reverse topological order
- std::vector<uint8_t> sccStack, dfsStack, output;
- uint8_t nextNode = 0, indexCount = 0;
- auto tarjanStep = [&]() {
- const uint8_t node = nextNode;
- auto& [index, lowLink, children] = nodes[node];
- if (index == UNDISCOVERED) { //found new node
- lowLink = index = indexCount++; //give it a new index
- dfsStack.push_back(node);
- sccStack.push_back(node);
- }
- if (!children.empty()) {
- const uint8_t child = children.back(), childIndex = nodes[child].index;
- children.pop_back();
- if (childIndex == UNDISCOVERED) nextNode = child; //dive into child if undiscovered
- else if (childIndex < lowLink) //if next node is a back-edge, inherit lowLink
- if (auto it = std::find(sccStack.begin(), sccStack.end(), child); it != sccStack.end())
- lowLink = childIndex;
- } else { //ran out of undiscovered children
- if (lowLink == index) { //found a root, splice out members to emit in *reverse*
- auto rit = std::find(sccStack.rbegin(), sccStack.rend(), node); //find start
- output.insert(output.end(), sccStack.rbegin(), std::next(rit)); //graft onto output
- sccStack.erase(std::next(rit).base(), sccStack.end()); //remove from stack
- }
- dfsStack.pop_back();
- if (!dfsStack.empty()) {
- nextNode = dfsStack.back(); //ascend back up the stack
- //make parent inherit lowLink from us
- if (lowLink < nodes[nextNode].lowLink) nodes[nextNode].lowLink = lowLink;
- } else { //ran out of parents
- nextNode = BLANK; //find a new node to start on that hasn't been discovered yet
- for (uint8_t i = 0; i < nodeCount && nextNode == BLANK; i++)
- if (nodes[i].index == UNDISCOVERED) nextNode = i;
- if (nextNode == BLANK) return false; //ran out of new nodes, done
- }
- }
- return true; //need another pass
- };
- while (tarjanStep()) { } //loop until we run out of nodes
Advertisement
Add Comment
Please, Sign In to add comment