int main(int argc, char *argv[]) { AdjacentGraph aG("Graph-3.txt"); veci topvertice; assert(topologicalSort(aG, topvertice) == false); AdjacentGraph aG1("Graph-4.txt"); assert(topologicalSort(aG1, topvertice) == true); std::cout << topvertice; return 0; }
// if has cycle, return false, else return true bool topologicalSort( int n, vector<int>& explored, vector<int>& path, unordered_map<int, vector<int>>& graph, vector<int>& result) { for(int i=0; i<graph[n].size(); i++) { int prereq = graph[n][i]; if ( path[prereq] ) { result.clear(); return false; } path[prereq] = true; if (!topologicalSort(prereq, explored, path, graph, result)){ result.clear(); return false; } path[prereq] = false; } if (!explored[n]) { result.push_back(n); } explored[n] = true; return true; }
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> result; vector<int> enterance (numCourses, true); //using map to stroe the graph, it's easy to search the edge for each node //the bool in pair means it is explored or not unordered_map<int, vector<int>> graph; for(int i=0; i<prerequisites.size(); i++){ graph[prerequisites[i].first].push_back( prerequisites[i].second ); enterance[prerequisites[i].second] = false; } //explored[] is used to record the node already checked! vector<int> explored(numCourses, false); //path[] is used to check the cycle during DFS vector<int> path(numCourses, false); for(int i=0; i<numCourses; i++){ if (!enterance[i] || explored[i]) continue; if (!topologicalSort(i, explored, path, graph, result)) return result; } //if there has one course hasn't been explored, means there is a cycle for (int i=0; i<numCourses; i++){ if (!explored[i]) return vector<int>(); } return result; }
/** * Topological sort helper method * * @param v process vertex v * @param topoStack */ void topologicalSort(Graph* g, int v, stack<int> &topoStack) { g->setMark(v, VISITED); // recur for all the vertices adjacent to this vertex for (int w = g->first(v); w < g->n(); w = g->next(v,w)) { if (g->getMark(w) == UNVISITED) topologicalSort(g, w, topoStack); } topoStack.push(v); // push current vertex to stack }
string AlienDictionary::alienOrder() { processGraph(); topologicalSort(); if (cycle) return ""; string retval; for (int i=rPostOrder.size()-1; i>=0; i--) { retval.push_back(nodeToChar[rPostOrder[i]]); } return retval; }
double network::gibbsSampling(int pos, int value, int t) { int size = nodes.size(); int sample[2][size]; srand((unsigned int) time(NULL)); //Forward Sampling topologicalSort(); for (int i = 0; i < size; i++) { int j = topOrder[i]; if (nodes.at(j).isObserved()) { sample[0][j] = nodes.at(j).getValue(); } else { sample[0][j] = (toss() <= (nodes.at(j).factor(1))); nodes.at(j).setValue(sample[0][j]); } } //GIBBS SAMPLING double sumMix = 0; double sum = 0; int mixSize = t*0.02; int mixStart = 0; for (int i = 1; i <= t; i++) { assign(sample[0]); for (int j = 0; j < 7; j++) { if ((*(nodeAt(j))).isObserved()) { sample[1][j] = sample[0][j]; } else { sample[1][j] = (toss() <= (pSamplingNode(j, 1))); (*(nodeAt(j))).setValue(sample[1][j]); } } //MIXING PROCESS if (i <= mixStart + mixSize) { sumMix += pSamplingNode(pos, value); } else { sum += pSamplingNode(pos, value); } if (i == mixStart + mixSize * 2) { if (abs(sumMix / mixSize - sum / mixSize) < 0.001) { sum += sumMix; }else{ sumMix = sum; sum = 0; mixStart += mixSize; } } //UPDATE OF PREVIOUS SAMPLE for (int j = 0; j < 7; j++) { sample[0][j] = sample[1][j]; } } return sum/(t-mixStart); }
void graph<T>::findDAGShortestPaths(node<T> *start) { cout << "For DAG with no negative weight edges:\n"; const int LARGENUMBER = 10000000; stack<node <T> *> *st = new stack<node <T> *>(); topologicalSort(st); if (hasCycle) { cout << "has cycle\n"; return; } stack<node<T> *> *st1 = st->cloneStack(); for (auto elem : nodelist) { node2parent[elem] = NULL; node2shortest[elem] = LARGENUMBER; } node2shortest[start] = 0; bool flag = false; while (!st1->isEmpty()) { node<T> *src = st1->dequeue(); if (src == start) flag = true; if (flag) { auto t_adjlist = src->get_adjlist(); for (auto elem : t_adjlist) { node<T> *dst = elem.first; int w = elem.second; cout << "src = " << src->get_data() << " and dst = " << dst->get_data() << "and w = " << w << "\n"; if (node2shortest[src] + w < node2shortest[dst]) { node2parent[dst] = src; node2shortest[dst] = node2shortest[src] + w; } } } } cout << "Shortest path lengths from " << start->get_data() << " are:\n"; for (auto elem : nodelist) { cout << elem->get_data() << ": " << node2shortest[elem] << "\n"; } cout << "Shortest path parents from " << start->get_data() << " are:\n"; for (auto elem : nodelist) { if (node2parent[elem]) cout << elem->get_data() << ": " << node2parent[elem]->get_data() << "\n"; } cout << "***********************\n"; }
void findTopoClass(Graph graph) { char temp[100]; int i, n, output[100]; if((n = topologicalSort(graph, output)) == 0) { return; } printf("The topological sort:\n"); for(i = 0; i < n; i++) { printf("%s\n", getVertex(graph, output[i])); } }
/// ----------------------------------------------------------------- /// /// @details This is the supporting recursive topological sort method. /// /// ----------------------------------------------------------------- void topologicalSort(uint32_t id, std::deque<uint32_t>& queue) { m_visited[id] = true; for (auto id : m_adjacent[id]) { if (m_visited[id] == false) { topologicalSort(id, queue); } } queue.push_back(id); }
void report() { // // report is considered a full transaction itself...but this isn't ever really // going to be run under production, only in debug. std::lock_guard<std::mutex> lock(m_mutex); std::deque<uint32_t> queue = topologicalSort(); while (queue.empty() == false) { std::cout << m_nodes[queue.back()].value << std::endl; queue.pop_back(); } }
void longestPath(Graph* g, int src, int dest) { // call the recursive topologicalSort function to store Topological Sort nodes stack<int> topoStack; // saves topological sorted nodes for (int i = 0; i < g->n(); i++) { // process all vertices one by one if (g->getMark(i) == UNVISITED) { topologicalSort(g, i, topoStack); } } // Initialize distances to all vertices as infinite and distance // to source as 0 int dist[g->n()]; // record longest path (weight) for nodes for (int i = 0; i < g->n(); i++) dist[i] = NINF; dist[src] = 0; cout << "from source node: " << src << " to" << endl; printDistArray(dist, g->n()); // Process vertices in topological order while (topoStack.empty() == false) { // Get the next vertex from topological order int u = topoStack.top(); topoStack.pop(); // Update distances of all adjacent vertices if (dist[u] != NINF) { // debug code for (int w=g->first(u); w<g->n(); w = g->next(u,w)) { if (dist[w] < dist[u] + g->weight(u, w)) { dist[w] = dist[u] + g->weight(u, w); } } } } // Print the calculated longest distances cout << endl; for (int i = 0; i < g->n(); i++) { cout << "dist[" << i << "]: "; (dist[i] == NINF) ? cout << "INF " : cout << dist[i] << " "; } for (int target = 0; target < g->n(); target++) { printLongestPath(g, dist, src, target); } }
/// ----------------------------------------------------------------- /// /// @details This is the topological sort kickoff method. Refer to this /// web reference for details on the implementation: http://www.geeksforgeeks.org/topological-sorting/ /// /// ----------------------------------------------------------------- std::deque<uint32_t> topologicalSort() { std::deque<uint32_t> queue; for (auto& node : m_visited) { node.second = false; } for (auto& node : m_visited) { if (node.second == false) { topologicalSort(node.first, queue); } } return queue; // Relying on move operator for efficient copy }
std::vector<std::string> Importer::getImportOrder(const std::string& baseScene) { std::vector<std::pair<std::string, std::string>> dependencies; for (const auto& scene : m_scenes) { const auto& name = scene.first; const auto& sceneRoot = scene.second; for (const auto& import : getScenesToImport(sceneRoot)) { dependencies.push_back( {import, name} ); } } auto sortedScenes = topologicalSort(dependencies); if (sortedScenes.empty()) { return { baseScene }; } return sortedScenes; }
std::vector<std::string> StyleMixer::getMixingOrder(const Node& _styles) { // Input must be a map of names to style configuration nodes. if (!_styles.IsMap()) { return {}; } // Dependencies are pairs of strings that form a DAG. // If style 'a' mixes style 'b', the dependency would be {'b', 'a'}. std::vector<std::pair<std::string, std::string>> dependencies; for (const auto& entry : _styles) { const auto& name = entry.first; const auto& config = entry.second; for (const auto& mix : getStylesToMix(config)) { dependencies.push_back({ mix, name.Scalar() }); } } return topologicalSort(dependencies); }
QList<ListDigraph::Node> ProcessModel::topolSort() { ListDigraph::NodeMap<int> nodes2pos(graph); // Map of nodes sorted topologically // Sort the nodes topologically topologicalSort(graph, nodes2pos); QMap<int, ListDigraph::Node> pos2nodes; // Topologically sorted nodes for (ListDigraph::NodeMap<int>::MapIt mi(nodes2pos); mi != INVALID; ++mi) { pos2nodes[*mi] = mi; } QList<ListDigraph::Node> tnodes; tnodes.clear(); tnodes.reserve(pos2nodes.size()); for (QMap<int, ListDigraph::Node>::iterator sti = pos2nodes.begin(); sti != pos2nodes.end(); sti++) { tnodes << sti.value(); } return tnodes; }
int main() { L_Graph g; createLGraph(S, &g); LGraph_addDEdge(&g, 0, 1); LGraph_addDEdge(&g, 1, 2); LGraph_addDEdge(&g, 3, 4); LGraph_addDEdge(&g, 4, 2); size_t s[S]; printf("%d\n\n", topologicalSort(&g, s)); int i; for (i = 0; i < S; ++i) printf("%d\n", s[i]); freeLGraph(&g); return (0); }
int main() { int a[10][10], flag[10], i, j, n; printf("Enter the number of nodes: "); scanf("%d", &n); for (i = 1; i <= n; i++) flag[i] = 0; printf("Enter the Adjacency Matrix:\n"); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { scanf("%d", &a[i][j]); if (a[i][j] == 1) flag[j]++; } } printf("The Topological Sorted Order is:\n"); topologicalSort(a, n, flag); return 0; }