[hihoCoder] 拓扑排序·一

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 <iostream>
 2 #include <vector>
 3 #include <queue>
 4 
 5 using namespace std;
 6 
 7 struct DirectedGraphNode {
 8     int label;
 9     vector<int> neighbors;
10     DirectedGraphNode(int i) : label(i) {}
11 };
12 
13 vector<DirectedGraphNode*> init_graph(int nodes) {
14     vector<DirectedGraphNode*> graph(nodes);
15     for (int i = 0; i < nodes; i++)
16         graph[i] = new DirectedGraphNode(i);
17     return graph;
18 }
19 
20 vector<int> compute_indegree(vector<DirectedGraphNode*>& graph) {
21     vector<int> 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<DirectedGraphNode*>& graph) {
29     vector<int> degrees = compute_indegree(graph);
30     int nodes = graph.size();
31     queue<int> 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<DirectedGraphNode*> 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 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值