NYOJ349 Sorting It All Out

 1 #include<stdio.h>

 2 #include<string.h> 

 3 bool map[30][30];

 4 int in[30],sort[30];

 5 int n,m,t;

 6 bool f1,f2;

 7 void solve(){

 8     int i,j,k,loc;

 9     int temp[30];

10     bool f=0;

11     for(i=0;i<n;i++)

12         temp[i]=in[i];

13     for(t=i=0;i<n;i++){

14         for(k=j=0;j<n;j++)

15             if(!temp[j]){

16                 k++;

17                 loc=j;

18             }

19         if(k==0){

20             f2=1;

21             return;

22         }

23         if(k>1) f=1;

24         sort[t++]=loc;

25         temp[loc]=-1;

26         for(j=0;j<n;j++)

27             if(map[loc][j])

28                 temp[j]--;

29         

30     }

31     if(!f) f1=1;

32 }

33 int main()

34 {

35     int i,p;

36     char a,b;

37     while(scanf("%d%d",&n,&m),n||m){

38         memset(map,0,sizeof(map));

39         memset(in,0,sizeof(in));

40         for(f1=f2=t=i=0;i<m;i++){

41             scanf("%*c%c<%c",&a,&b);

42             if(!f1&&!f2){

43                 map[a-'A'][b-'A']=1;

44                 in[b-'A']++;

45                 solve();

46                 p=i+1;

47             }

48         }

49         if(f1){

50             printf("Sorted sequence determined after %d relations: ",p);

51             for(i=0;i<t;i++)

52                 printf("%c",sort[i]+'A');

53             puts(".");

54         }else if(f2){

55             printf("Inconsistency found after %d relations.\n",p);

56             

57         }else puts("Sorted sequence cannot be determined.");

58     }

59     return 0;
//一道典型的拓扑排序的题目,纠结了好长时间!!

你可能感兴趣的:(sort)