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

来源:互联网 发布:淘宝开店多久自动关闭 编辑:程序博客网 时间:2024/04/24 20:51

题意:给定n个字母,和m个组两两字母间的偏序关系,求唯一的拓扑序列。

解题思路:

1,解决的思路是有先后关系的,即先要判断能不能形成拓扑序列,若不能输出erro,若能形成拓扑序列,在判断拓扑序列的唯一性,若拓扑序不唯一,输出error,若唯一则输出拓扑序列。这是大体的解决思路,具体的在慢慢分析。

2,题目要求即使数据还没输入完已经确定某种关系是就输出这种关系,所以我们在读入一组数据后就进行一次拓扑排序,并检验函数的返回值。

3,如何判断是否存在拓扑序,若图中有环则不存在拓扑序,使用无前区的定点优先的拓扑排序算法(队列)很容易判断是否有环(不断删除入度为零的点并更新其他点的入度)

4,若存在拓扑序,如何判断拓扑序是否唯一,我们实时可以检查入度为零的点的个数,若存在多个入度为零的点(除去已经删除的入度为零的点)则拓扑序不唯一,但在无前区的定点优先的拓扑排序算法不易实现(在这里卡了好久),所以我们换种思路实时检查队列中的点的个数,若大于1,则拓扑序不唯一。

5,关于输出,可以采用找到结果立即输出的方法,也可以等输入完毕后再输出结果,主要是在输入未完成时已经求出结果后,要跳过之后的其他输入。

附上两种输出的AC代码,有一种是参考别人的


另外:我采用的数据结构是链式向前星,可以大大提高时间效率。

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.


Memory: 664 KB Time: 0 MSLanguage: G++ Result: Accepted

#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<list>#include<iostream>#include<map>#include<queue>#include<set>#include<stack>#include<vector>using namespace std;#define MAX_N 30const int INF = 0x3f3f3f3f;int n, m;int que[MAX_N];//保存入度为零的点的队列int indegree[MAX_N];//保存入度的数组int indeg[MAX_N];//保存入度的临时数组int top;int head[MAX_N];struct node{    int to, next;} edge[MAX_N * MAX_N];int init()//初始化{    top = 0;    memset(head, -1, sizeof(head));    memset(indegree, 0, sizeof(indegree));}void add_edge(int u, int v)//添加边的函数{    edge[top].to = v;    edge[top].next = head[u];    head[u] = top++;}int iq;int topo_sort(){    iq = 0;    int res = 0;    //查找入度为零的点压入队列,并临时储存入度    for(int i = 0 ; i < n ; i++)    {        indeg[i] = indegree[i];        if(indegree[i] == 0)        {            que[iq++] = i;        }    }    for(int i = 0 ; i < iq ; i++)    {        if(i + 1 < iq)//队列头部和队列尾部间隔大于一,说明里面存在入度为零的点个数大于一,拓扑序不唯一        {            res = 1;        }        for(int k = head[que[i]]  ; k != -1; k = edge[k].next)        {            indeg[edge[k].to]--;//更新删除点后其指向的其他点的入度            if(indeg[edge[k].to] == 0)            {                que[iq++] = edge[k].to;            }        }    }    if(iq < n - 1) return -1;//有环    if(res) return 0;//拓扑序不唯一    return 1;//正常}int main(){    while(scanf("%d%d", &n, &m) && (n + m))    {        init();        char s[5];        int err = -1;        int ans = -1;        for(int i = 0 ; i < m ; i++)        {            scanf("%s", &s);            if (err != -1 || ans != -1) continue;//已经得出结果跳过其他输入            int u = s[0] - 'A';            int v = s[2] - 'A';            indegree[v]++;            add_edge(u, v);            int res = topo_sort();            if(res == -1) err = i + 1;            else if(res == 1) ans = i + 1;        }        if (ans != -1)        {            printf("Sorted sequence determined after %d relations: ", ans);            for(int i = 0 ; i < iq ; i++)            {                printf("%c", que[i] + 'A');            }            printf(".\n");        }        else if (err != -1)        {            printf("Inconsistency found after %d relations.\n", err);        }        else        {            printf("Sorted sequence cannot be determined.\n");        }    }    return 0;}



Memory: 664 KB Time: 0 MSLanguage: G++ Result: Accepted
#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<list>#include<iostream>#include<map>#include<queue>#include<set>#include<stack>#include<vector>using namespace std;const int INF = 0x3f3f3f3f;#define MAX_N 30int n , m;int indegree[MAX_N];int tmp_indegree[MAX_N];int top;int head[MAX_N];int que[MAX_N];struct node{    int to, next;};node edge[MAX_N * MAX_N];void init(){    top = 0;    memset(head, -1, sizeof(head));    memset(indegree, 0, sizeof(indegree));}void add_edge(int u, int v){    edge[top].to = v;    edge[top].next = head[u];    head[u] = top++;}int iq;int top_sort(){    int res= 0;    iq = 0;    for(int i = 0 ; i < n ; i++)    {        tmp_indegree[i] = indegree[i];        if(indegree[i] == 0)        {            que[iq++] = i;        }    }    for(int i = 0 ; i < iq ; i++)    {        if(i + 1 < iq) res = 1;        for(int k = head[que[i]]  ; k != -1; k = edge[k].next)        {            tmp_indegree[edge[k].to]--;            if(tmp_indegree[edge[k].to] == 0)            {                que[iq++] = edge[k].to;            }        }    }    if(iq < n - 1) return -1;    if(res) return 0;    return 1;}int main(){    while(~scanf("%d%d", &n, &m)&& n)    {        init();        int flag = -2;        for(int i = 0 ; i < m ; i++)        {            int u, v;            char s[10];            scanf("%s", &s);            if(flag != -2 && flag != 0) continue;            u = s[0] - 'A';            v = s[2] - 'A';            indegree[v]++;            add_edge(u, v);            flag = top_sort();            if(flag == -1)            {                printf("Inconsistency found after %d relations.\n", i + 1);            }            else if(flag == 1)            {                printf("Sorted sequence determined after %d relations: ", i + 1);                for(int i = 0 ; i < iq ; i++)                {                    printf("%c", que[i] + 'A');                }                printf(".\n");            }        }        flag = top_sort();        if(flag == 0)            printf("Sorted sequence cannot be determined.\n");    }    return 0;}


附送一组测试数据可以检测程序的正确性:

4 6D<BD<AD<CC<AC<BA<B10 40C<IE<GA<JF<BD<EF<DC<BE<HG<ID<BC<HA<BJ<ID<GA<EC<GE<BH<GC<AF<JB<GD<JE<JD<HC<FB<JG<JB<HD<AF<IA<HC<EF<HA<GB<IF<AH<JF<GF<EC<J15 60B<MM<HN<GN<EI<DB<DA<JO<DD<JF<EI<LF<BI<CC<EI<KI<JA<EB<LG<JA<GN<HH<JK<NK<EF<JC<DK<MG<LF<HM<LA<KB<KE<LB<HF<DM<EM<GN<LO<JD<HB<OB<CA<LI<BF<LC<LA<CN<OA<BF<CK<JC<GO<EI<OD<EI<NF<NM<JH<LN<D15 60B<MM<HN<GN<EI<DB<DA<JO<DD<JF<EI<LF<BI<CC<EI<KI<JA<EB<LG<JA<GN<HH<JK<NK<EF<JC<DK<MG<LF<HM<LA<KB<KE<LB<HF<DM<EM<GN<LO<JD<HO<BB<CA<LI<BF<LC<LA<CN<OA<BF<CK<JC<GO<EI<OD<EI<NF<NM<JH<LN<D26 325J<IL<PK<SM<XK<EH<WZ<SG<RF<RA<YV<DP<XP<WM<SR<AG<VC<HO<RA<SN<CV<YA<IF<ZV<QV<RH<IQ<TM<QF<AJ<XM<DC<QD<EV<FB<TX<UD<UG<YV<BB<JN<UK<ZP<SE<UO<YM<ZC<IF<SG<PO<JC<SW<UZ<YD<LH<TB<QX<WD<IK<BR<LL<XS<QK<FB<RC<LO<BY<SF<YX<TS<UC<WO<PB<ZV<UC<XH<UO<UV<WD<AO<XG<DP<AD<XE<TS<TC<TH<OJ<QK<HZ<QZ<WI<TJ<AZ<EF<LQ<UJ<SN<HJ<EB<DM<IK<RZ<XB<YP<YR<EF<OR<PC<AD<YD<ZB<XM<AI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A<SC<BQ<JF<PM<GR<JN<OL<II<KB<OJ<EC<JH<TQ<AQ<SL<BK<TO<TA<GH<GC<RP<BH<QC<EA<EI<JR<FM<DH<DN<TC<OI<TD<RC<KH<PC<IC<PN<AR<BH<MR<IC<QI<EQ<IQ<DC<SD<LN<BQ<KC<GP<JC<AJ<TQ<LD<PR<GS<TH<KI<OD<EI<BP<KK<EN<GC<FM<TS<BA<KS<EA<FA<TP<GR<ED<IF<KI<SG<JH<FG<SL<FP<IM<LG<IN<PB<TL<PJ<KC<HB<KA<IG<EG<TN<MM<BH<RD<JM<EF<GQ<MD<SH<BN<JQ<EG<OC<NH<AP<TQ<BL<SR<SN<LL<GQ<RF<OA<RL<EQ<PE<TM<RM<SL<OA<LR<PH<JL<KM<PA<ML<TR<TL<RS<JN<EF<IA<DD<FQ<OJ<OO<EC<LA<BN<KN<FG<KD<TN<IH<LM<IL<J0 0

Sorted sequence determined after 6 relations: DCAB.Sorted sequence determined after 29 relations: CFDAEBHGJI.Sorted sequence cannot be determined.Inconsistency found after 48 relations.Sorted sequence determined after 318 relations: GMNVKCHFOBRJDZLPXAYSEIWQTU.Sorted sequence determined after 25 relations: ABCDEFGHIJKLMNOPQRSTUVWXYZ.Sorted sequence determined after 7 relations: BADCE.Sorted sequence determined after 158 relations: HNAMGIPCTBJFRLEODKSQ.Inconsistency found after 35 relations.Sorted sequence cannot be determined.Sorted sequence determined after 7 relations: ABDEC.Sorted sequence cannot be determined.Sorted sequence determined after 11 relations: ACDBFE.Sorted sequence cannot be determined.Sorted sequence cannot be determined.Sorted sequence determined after 179 relations: CHQNAMDLRFPGISBJOKET.

0 0