#include <bits/stdc++.h>using namespace STD; vector< vector<char> >Vintn,m,use[ -],cnt[ -];Charans[ -],s[Ten];intTopsort (intx) {inti,j,t[ -],f=1, R,c;memset(ANS,0,sizeof(ans)); for(i=0; i< -; i++) T[i]=cnt[i]; C=0; R=0; while(x--) {c=0; for(i=0; i<n; i++) {if(t[i]==0) {j=i; C + +; } }if(c>=1) {if(c>1) f=0; for(i=0; I<v[j].size (); i++) {t[v[j][i]]--; } ans[r++]=j+' A '; t[j]=-1; ans[r]=0; }Else if(c==0)return-1; }if(f)returnRElse return 0;}intMain () {intFlag,i,num,ok,k; while(~scanf("%d%d", &n,&m)) {if(n==0&&m==0) Break; V.clear (); V.resize (n);memset(Use,0,sizeof(use));memset(CNT,0,sizeof(CNT)); ok=0; num=0; for(i=0; i<m; i++) {scanf('%s ', s); cnt[s[2]-' A ']++; v[s[0]-' A '].push_back (s[2]-' A ');if(!use[s[0]-' A ']) {num++; use[s[0]-' A ']=1; }if(!use[s[2]-' A ']) {num++; use[s[2]-' A ']=1; }if(ok==0) {intT=topsort (num);if(t==n) {ok=1; k=i+1; }Else if(t==-1) {ok=-1; k=i+1; } } }if(!ok)printf("Sorted sequence cannot be determined.\n");Else if(ok==1)printf("Sorted sequence determined after%d relations:%s.\n", K,ans);Else printf("inconsistency found after%d relations.\n", k); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Zoj 1060 Sorting It all out (topological sort)