lintcode:Topological Sorting
来源:互联网 发布:交换机的tftp端口号 编辑:程序博客网 时间:2024/05/29 14:29
Topological Sorting
07:18
Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge
A -> B
in graph, A must before B in the order list. - The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.
Notice
You can assume that there is at least one topological order in the graph.
For graph as follow:
顺便贴一个topology的视频:https://www.youtube.com/watch?v=ddTC4Zovtbc
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */class Solution { private: void topSortHelper(DirectedGraphNode* curNode, stack<DirectedGraphNode*> &auxStack, set<int> &visited) { visited.insert(curNode->label); for (int i=0; i<curNode->neighbors.size(); i++) { if (visited.find(curNode->neighbors[i]->label) == visited.end()) { topSortHelper(curNode->neighbors[i], auxStack, visited); } } auxStack.push(curNode);//当这个节点已经visit 过它所有的子节点的之后,就把它发到stack中,所以stack的最上层肯定是依赖性最小的,食物链最高的节点 } public: /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { // write your code here set<int> visited; stack<DirectedGraphNode*> auxStack; for (int i=0; i<graph.size(); i++) { if (visited.find(graph[i]->label) == visited.end()) { topSortHelper(graph[i], auxStack, visited); } } vector<DirectedGraphNode*> retVtr; while (auxStack.size() > 0) { retVtr.push_back(auxStack.top()); auxStack.pop(); } return retVtr; }};
0 0
- Lintcode - Topological Sorting
- lintcode:Topological Sorting
- lintcode:Topological Sorting
- LintCode Topological Sorting
- Topological sorting
- Topological sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Ural 1280. Topological Sorting
- ural 1280. Topological Sorting
- ural 1280Topological Sorting
- timus 1280 Topological Sorting
- [Random Coding]Topological Sorting
- ural 1280. Topological Sorting
- [刷题]Topological Sorting
- 二代旅游网站程序管理系统V1.0正式发布
- UESTC 1144 Big Brother
- reuseport+fastsocket
- [CODEVS1343][HNOI]蚱蜢(平衡树splay)
- mapreduce工作原理
- lintcode:Topological Sorting
- Hadoop自定义 inputformat 和outputformat 实现图像的读写
- ZOJ3805 Machine I型和L型的管道最少多宽?(贪心)
- C++实验2——计算出标准体重,输出体重状态
- 扑克牌大小
- IOS开发之OC学习笔记(中)
- Lucene 4.X 倒排索引原理与实现: (2) 倒排表的格式设计
- unity Game Center iOS 认证失败social.authenticate
- 【c++】字符串最后一个单词的长度