首页 > 代码库 > poj-2367-拓扑排序-水

poj-2367-拓扑排序-水

今天重温了一下拓扑排序,做道水题开个头。思路就不写了,很暴力。

AC代码:

 1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <vector> 5 #include <cstring> 6 using namespace std; 7 int arr[109][109]; 8 bool vis[109], inq[109]; 9 int n;10 queue<int> anse;11 void init()12 {13     memset(vis, 0, sizeof(vis));14     memset(inq, 0, sizeof(inq));15     memset(arr, 0, sizeof(arr));16     int a;17     for(int i = 1; i <= n; i++) {18         while(scanf("%d", &a) && a ) {19             arr[i][a] = 1;20             vis[a] = 1;21         }22     }23     for(int i = 1; i <= n; i++) {24         if(!vis[i]) {25             anse.push(i);26             for(int j = 1; j <= n; j++) {27                 arr[i][j] = 0;28             }29             inq[i] = 1;30         }31     }32 }33 void findhead()34 {35     for(int i = 1; i <= n; i++) {36         int flag = 0;37         if(!inq[i]) {38             for(int j = 1; j <= n; j++) {39                 if(arr[j][i] == 1) { flag = 1; break;}40             }41             if(!flag) {42                 anse.push(i);43                 for(int j = 1; j <= n; j++) {44                     arr[i][j] = 0;45                 }46                 inq[i] = 1;47             }48         }49     }50 }51 void work()52 {53     init();54     while(anse.size() < n) {55         findhead();56     }57     printf("%d", anse.front());58     anse.pop();59     while(!anse.empty()) {60         printf(" %d", anse.front());61         anse.pop();62     }63     printf("\n");64 }65 int main()66 {67     while(scanf("%d", &n) != EOF) work();68     return 0;69 }

 

poj-2367-拓扑排序-水