LintCode-拓扑排序
来源:互联网 发布:淘宝是马云还是日本人 编辑:程序博客网 时间:2024/05/18 01:06
给定一个有向图,图节点的拓扑排序被定义为:
- 对于每条有向边A--> B,则A必须排在B之前
- 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点
找到给定图的任一拓扑排序
解法:
计算所有节点的入度
选择一个入度为零的节点输出,并将其子节点的入度减1
循环直到所有节点输出
第一次超时了,后来减少了查表次数和vector的erase操作通过了
class Solution {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 map<DirectedGraphNode*, int> numMap; for(int i = 0; i < graph.size(); ++i) { DirectedGraphNode* node = graph[i]; for(int j = 0; j < node->neighbors.size(); ++j) { DirectedGraphNode* child = node->neighbors[j]; auto it = numMap.find(child); if(it != numMap.end()) { it->second += 1; }else { numMap[child] = 1; } } } vector<DirectedGraphNode*> r; int base = 0; while(base < graph.size()) { for(int i = base; i < graph.size(); ++i) { DirectedGraphNode* node = graph[i]; auto it = numMap.find(node); if(it == numMap.end() || it->second == 0) { DirectedGraphNode* tmp = graph[base]; graph[base] = node; graph[i] = tmp; ++base; r.push_back(node); for(int j = 0; j < node->neighbors.size(); ++j) { numMap[node->neighbors[j]] -= 1; } break; } } } return r; }};
0 0
- lintcode-拓扑排序-127
- LintCode-拓扑排序
- LintCode 127-拓扑排序
- lintcode(127)拓扑排序
- 拓扑排序-LintCode
- Lintcode 拓扑排序
- LintCode 解题记录 17.10.14 拓扑排序
- Lintcode:拓扑排序(深度优先搜索,广度优先搜索)
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- (4.2.36.1)HTTP之OkHttp(一): Okhttp使用详解
- 关于SPCOMM使用中碰到的问题
- jquery中each循环常见问题
- 分页
- 第24个python程序:更多练习
- LintCode-拓扑排序
- 范德蒙行列式计算以应用
- 分布式架构初探-Leader Training 一期项目小分队成立了
- mongoDB 使用手册
- Http状态码之:301、302重定向
- sql 优化
- 数组应用之去除重复元素、Arrays数组工具的使用、二维数组、数组总结
- .Net 异常处理
- linux的IPC机制1-管道