博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[hihoCoder] 拓扑排序·一
阅读量:5333 次
发布时间:2019-06-15

本文共 1960 字,大约阅读时间需要 6 分钟。

The hints of the problem has given detailed information to implement the topological sorting algorithm. In fact, the toposort algorithm of the hint is the BFS version, which uses the indegrees of each node.

The code is as follows.

1 #include 
2 #include
3 #include
4 5 using namespace std; 6 7 struct DirectedGraphNode { 8 int label; 9 vector
neighbors;10 DirectedGraphNode(int i) : label(i) {}11 };12 13 vector
init_graph(int nodes) {14 vector
graph(nodes);15 for (int i = 0; i < nodes; i++)16 graph[i] = new DirectedGraphNode(i);17 return graph;18 }19 20 vector
compute_indegree(vector
& graph) {21 vector
degrees(graph.size(), 0);22 for (int i = 0; i < (int)graph.size(); i++)23 for (int j = 0; j < (int)graph[i] -> neighbors.size(); j++)24 degrees[graph[i] -> neighbors[j]]++;25 return degrees;26 }27 28 bool noCycle(vector
& graph) {29 vector
degrees = compute_indegree(graph);30 int nodes = graph.size();31 queue
zeros;32 for (int i = 0; i < (int)degrees.size(); i++)33 if (!degrees[i]) zeros.push(i);34 while (!zeros.empty()) {35 int zero = zeros.front();36 zeros.pop();37 for (int i = 0; i < (int)graph[zero] -> neighbors.size(); i++)38 if (--degrees[graph[zero] -> neighbors[i]] == 0)39 zeros.push(graph[zero] -> neighbors[i]);40 nodes--;41 }42 return nodes == 0;43 }44 45 int main(void) {46 int cases;47 scanf("%d", &cases);48 for (int i = 0; i < cases; i++) {49 int nodes, edges;50 scanf("%d %d", &nodes, &edges);51 vector
graph = init_graph(nodes);52 int node, neigh;53 for (int j = 0; j < edges; j++) {54 scanf("%d %d", &node, &neigh);55 graph[node - 1] -> neighbors.push_back(neigh - 1);56 }57 if (noCycle(graph)) printf("Correct\n");58 else printf("Wrong\n");59 }60 return 0;61 }

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4606384.html

你可能感兴趣的文章
C#中结构体与字节流互相转换
查看>>
WIN10配置MongoDB
查看>>
iOS resign code with App Store profile and post to AppStore
查看>>
python 表格操作
查看>>
LeetCode 84. Largest Rectangle in Histogram
查看>>
LeetCode Two Sum III - Data structure design
查看>>
session和xsrf
查看>>
Cookie与Session
查看>>
配置redis外网可访问
查看>>
跟随大神实现简单的Vue框架
查看>>
Linux目录结构
查看>>
learning awk
查看>>
LeetCode-Strobogrammatic Number
查看>>
luoguP3414 SAC#1 - 组合数
查看>>
五一 DAY 4
查看>>
关于System.__ComObject一些问题
查看>>
java stringbuffer二
查看>>
[hihoCoder] 拓扑排序·一
查看>>
(转)接口测试用例设计(详细干货)
查看>>
js Math对象方法 (个人学习笔记)
查看>>