POJ1094-Solve All It Out
1 #include<iostream> 2 #include<fstream> 3 #include<cstring> 4 5 using namespace std; 6 #define MAXN 28 7 8 bool adj[MAXN][MAXN]; 9 int indegree[MAXN]; 10 char str[MAXN]; 11 int n, m; 12 13 14 15 16 int topo_sort() 17 { 18 int i,j,k; 19 int flag = true; 20 memset(indegree,0,sizeof(indegree)); 21 memset(str,'\0',sizeof(str)); 22 for(i=1; i<=n; i++) 23 { 24 for(j=1; j<=n; j++) 25 if(adj[i][j]) 26 indegree[j]++; 27 } 28 for(i=1; i<=n; i++) 29 { 30 k = 0; 31 for(j=1; j<=n; j++) 32 { 33 if(indegree[j]==0) 34 { 35 if(k==0) k = j; 36 else flag = false; 37 } 38 } 39 if(k==0) return 0; 40 indegree[k] = -1; 41 str[i-1] = k+'A'-1; 42 for(j=1; j<=n; j++) 43 { 44 if(adj[k][j]) 45 indegree[j]--; 46 } 47 } 48 49 if(flag) return 1; 50 else return 2; 51 } 52 53 int main() 54 { 55 56 int i, a, b, result; 57 char s[4]; 58 while (scanf("%d %d", &n, &m),m+n) 59 { 60 memset(adj,false,sizeof(adj)); 61 bool h=false; 62 for(i=1; i<=m; i++) 63 { 64 scanf("%s", s); 65 a = s[0]-'A'+1; 66 b = s[2]-'A'+1; 67 adj[a][b] = true; 68 if(h) continue; 69 result = topo_sort(); 70 if(result == 1) 71 { 72 printf("Sorted sequence determined after %d relations: %s.\n",i,str); 73 h = true; 74 } 75 if(result == 0) 76 { 77 printf("Inconsistency found after %d relations.\n",i); 78 h = true; 79 } 80 } 81 if(!h) 82 printf("Sorted sequence cannot be determined.\n"); 83 } 84 85 return 0; 86 }