7-34 任务调度的合理性 (25分)--拓扑排序

创建一个队列,先将所有入度为0(不用依赖其他点)的点入队,然后while循环

循环出队,如果该指向的点的入度减一,然后判断减一后入度是不是为零,如果是,则这个点入队。

每一次入队的时候计数cnt加一。当排序完(while退出)以后判断cnt的值是不是等于点的总数,若等于,说明可行(任务全都可以完成);若不等,则说明不可行。

 1 #include <iostream>
 2 using namespace std;
 3 int q[101];
 4 int r = -1, f = -1;
 5 void enq(int x) { q[++f] = x; }
 6 int deq() { return q[++r]; }
 7 int main()
 8 {   
 9     int cnt=0;
10     int m[101][101] = { 0 };
11     int in_dgr[101] = { 0 };
12     int n; cin >> n;
13     for (int i = 1; i <= n; i++)
14     {
15         int t; cin >> t;
16         in_dgr[i] += t;
17         for (int j = 0; j < t; j++)
18         {
19             int t2; cin >> t2;
20             m[t2][i] = 1;
21         }
22     }
23     for (int i = 1; i <= n; i++)
24     {
25         if (in_dgr[i] == 0)
26         {
27             enq(i);
28             cnt++;
29         }
30     }
31     while (r < f)
32     {
33         int temp = deq();
34         for (int i = 1; i <= n; i++)
35         {
36             if (m[temp][i] == 1)
37             {
38                 in_dgr[i]--;
39                 if (in_dgr[i] == 0)
40                 {
41                     enq(i);
42                     cnt++;
43                 }
44             }
45         }
46     }
47     if (cnt != n)cout << "0";
48     else cout << "1";
49 }
原文地址:https://www.cnblogs.com/2020R/p/12609369.html