POJ 题目1094Sorting It All Out(拓扑排序)

来源:互联网 发布:日本女孩长相知乎 编辑:程序博客网 时间:2024/04/20 07:39
Sorting It All Out
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 28575 Accepted: 9875

Description

An ascending sorted sequence of distinct values is one in which some form of a less-than operator is used to order the elements from smallest to largest. For example, the sorted sequence A, B, C, D implies that A < B, B < C and C < D. in this problem, we will give you a set of relations of the form A < B and ask you to determine whether a sorted order has been specified or not.

Input

Input consists of multiple problem instances. Each instance starts with a line containing two positive integers n and m. the first value indicated the number of objects to sort, where 2 <= n <= 26. The objects to be sorted will be the first n characters of the uppercase alphabet. The second value m indicates the number of relations of the form A < B which will be given in this problem instance. Next will be m lines, each containing one such relation consisting of three characters: an uppercase letter, the character "<" and a second uppercase letter. No letter will be outside the range of the first n letters of the alphabet. Values of n = m = 0 indicate end of input.

Output

For each problem instance, output consists of one line. This line should be one of the following three: 

Sorted sequence determined after xxx relations: yyy...y. 
Sorted sequence cannot be determined. 
Inconsistency found after xxx relations. 

where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence. 

Sample Input

4 6A<BA<CB<CC<DB<DA<B3 2A<BB<A26 1A<Z0 0

Sample Output

Sorted sequence determined after 4 relations: ABCD.Inconsistency found after 2 relations.Sorted sequence cannot be determined.

Source

East Central North America 2001

ac代码

#include<stdio.h>#include<string.h>int map[30][30],dig[30],v[30];int as[30];int n,m;int topu(){int i,j,u,k=0,digg[30],w=1;//memset(v,0,sizeof(v));for(i=0;i<n;i++)digg[i]=dig[i];for(i=0;i<n;i++){int num=0;for(j=0;j<n;j++){if(digg[j]==0){u=j;//dig[j]--;num++;}}if(num==0)return 0;if(num>1)w=0;//因为可能还有环,在这直接return -1,waas[k++]=u;//v[u]=1;digg[u]=-1;for(j=0;j<n;j++){if(map[u][j]==1){digg[j]--;}}}if(!w)return -1;return 1;}int main(){//int n,m;while(scanf("%d%d",&n,&m)!=EOF,n||m){char a,b;int i,j,ans,w=0,u;memset(map,0,sizeof(map));memset(dig,0,sizeof(dig));for(i=0;i<m;i++){//int ans;getchar();scanf("%c<%c",&a,&b);if(w)continue;dig[b-'A']++;map[a-'A'][b-'A']=1;ans=topu();if(ans==1){w=1;//u=i;printf("Sorted sequence determined after %d relations: ",i+1);for(j=0;j<n;j++){printf("%c",as[j]+'A');}printf(".\n");}elseif(ans==0){w=1;printf("Inconsistency found after %d relations.\n",i+1);}}if(w==0){printf("Sorted sequence cannot be determined.\n");}}}


0 0
原创粉丝点击