http://poj.org/problem?id=1094
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<vector> 6 #include<queue> 7 #include<cstdlib> 8 using namespace std; 9 const int maxn=100000+5; 10 vector <int> g[maxn]; 11 int du[maxn],n,m,l[maxn]; 12 bool vis[1000][1000]; 13 int toposort() 14 { 15 memset(du,0,sizeof(du)); 16 for(int i=0; i<n; i++) 17 { 18 for(int j=0; j<g[i].size(); j++) 19 { 20 du[g[i][j]]++; 21 } 22 } 23 int tot=0; 24 bool flag=false; 25 queue<int>q; 26 for(int i=0; i<n; i++) 27 { 28 if(!du[i]) q.push(i); 29 } 30 while(!q.empty()) 31 { 32 if(q.size()>1) 33 { 34 flag=true; 35 } 36 int x=q.front(); 37 q.pop(); 38 l[tot++]=x; 39 for(int j=0; j<g[x].size(); j++) 40 { 41 int t=g[x][j]; 42 du[t]--; 43 if(!du[t]) q.push(t); 44 } 45 } 46 if(tot!=n) return 1; 47 else if(flag) { 48 return 2; 49 } 50 return 0; 51 } 52 int main() 53 { 54 char c1,c2; 55 while(scanf("%d%d",&n,&m)) 56 { 57 getchar(); 58 for(int i=0;i<maxn;i++) 59 { 60 g[i].clear(); 61 } 62 bool flag1=false,flag2=false; 63 memset(vis,0,sizeof(vis)); 64 if(n==0&&m==0) break; 65 for(int i=1; i<=m; i++) 66 { 67 scanf("%c<%c",&c1,&c2); 68 getchar(); 69 if(!flag1&&!flag2) 70 { 71 if(vis[c2-'A'][c1-'A']) 72 { 73 flag1=true; 74 printf("Inconsistency found after %d relations. ",i); 75 continue; 76 } 77 if(!vis[c1-'A'][c2-'A']) 78 { 79 g[c1-'A'].push_back(c2-'A'); 80 vis[c1-'A'][c2-'A']=1; 81 } 82 int k=toposort(); 83 if(k==0) 84 { 85 printf("Sorted sequence determined after %d relations: ",i); 86 for(int j=0; j<n; j++) printf("%c",l[j]+'A'); 87 printf(". "); 88 flag2=true; 89 } 90 else if(k==1) 91 { 92 flag1=true; 93 printf("Inconsistency found after %d relations. ",i); 94 } 95 } 96 } 97 if(!flag1&&!flag2) 98 { 99 printf("Sorted sequence cannot be determined. "); 100 } 101 } 102 return 0; 103 }