UVa-10305 Ordering Tasks
1 #include <bits/stdc++.h> 2 3 const int maxn = 102; 4 using namespace std; 5 6 int G[maxn][maxn]; 7 int n,m; 8 int vis[maxn]; 9 int topo[maxn],tmpN; 10 bool dfs(int u) 11 { 12 vis[u] = -1;//under visting 13 for(int v = 1; v <= n; v ++) 14 { 15 if(G[u][v]) 16 { 17 if(vis[v]<0) return false;//loop 18 else if(!vis[v] && !dfs(v)) return false; 19 } 20 } 21 vis[u] = 1; 22 topo[--tmpN]=u; 23 24 return true; 25 } 26 27 bool toposort() 28 { 29 tmpN = n; 30 for(int u = 1; u <= n; u ++) 31 { 32 if(!vis[u]) 33 if(!dfs(u)) 34 return false; 35 } 36 return true; 37 } 38 39 void solve() 40 { 41 if(toposort()) 42 { 43 for(int i = 0; i < n; i ++) 44 cout << topo[i] << " "; 45 cout << endl; 46 } 47 } 48 49 int main() 50 { 51 while(cin >> n >> m) 52 { 53 memset(G,0,sizeof(G)); 54 memset(vis,0,sizeof(vis)); 55 while(m --) 56 { 57 int tmp1,tmp2; 58 cin >> tmp1 >> tmp2; 59 G[tmp1][tmp2] = 1; 60 } 61 solve(); 62 } 63 return 0; 64 }