建立一個隊列,先將全部入度爲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 }