建立一个队列,先将全部入度为0(不用依赖其余点)的点入队,而后while循环:ios
循环出队,若是该指向的点的入度减一,而后判断减一后入度是否是为零,若是是,则这个点入队。spa
每一次入队的时候计数cnt加一。当排序完(while退出)之后判断cnt的值是否是等于点的总数,若等于,说明可行(任务全均可以完成);若不等,则说明不可行。code
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 }