Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9696 Accepted Submission(s): 3790
ios
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 #define MAX 505 5 int map[MAX][MAX]; 6 int main() 7 { 8 int p1, p2; 9 int n, m; 10 int indegree[MAX], i, j; 11 priority_queue<int, vector<int>, greater<int> > q; //用優先隊列保存入度爲0的頂點,這樣就能夠使輸出的頂點是從小到大的順序 12 while(cin>>n>>m) 13 { 14 while(!q.empty()) 15 q.pop(); 16 for (i=0; i<n; i++) 17 indegree[i] = 0; 18 for (i=0; i<n; i++) 19 for(j=0; j<n; j++) 20 map[i][j] = 0; 21 for (i=0; i<m; i++) 22 { 23 cin>>p1>>p2; 24 if(!map[p1-1][p2-1]) //必定要加判斷,不然有可能輸入重邊,結果就會WA 25 { 26 map[p1-1][p2-1] = 1; 27 indegree[p2-1]++; 28 } 29 } 30 for (i=0; i<n; i++) 31 if (!indegree[i]) 32 q.push(i+1); 33 while (!q.empty()) 34 { 35 j = q.top(); 36 q.pop(); 37 cout<<j; 38 for (i=0; i<n; i++) 39 if (map[j-1][i]) 40 { 41 indegree[i]--; 42 if (!indegree[i]) 43 q.push(i+1); 44 } 45 if(!q.empty()) 46 cout<<" "; 47 } 48 cout<<endl; 49 } 50 return 0; 51 }