[拓扑排序] PKU 1094 Sorting It All Out

第一道拓扑排序,拓扑排序的过程很简单:每次拿出一个入度为0的顶点放入solu[]尾部,并将它可以直接到达的顶点的入度减1;

对这道题需要得到唯一顺序,每次发现有多个入度为0的顶点时,说明还未排好序,此时不应该直接返回cannot be determined而是对所有入度为0的顶点执行上述操作,如果发现到某一步没有入度为0的顶点了说明出现矛盾,此时返回出现矛盾;

PS:这道题的输入有重复。

# include <cstdio>

# include <cstring>



# define N 26 + 1



int n, m;

int in[N], tmp[N];

char ans[N], g[N][N];



int topsort(void)

{

    bool multi = false;

    int cnt, i, first;

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

         tmp[i] = in[i];

     char vis[N];

     memset(vis, 0, sizeof(char)*n);

     int c = 0;

    while(c < n)

    {

        cnt = 0;

        for (i = 0; i < n; ++i)    if (!vis[i] && tmp[i] == 0)

        {

            ++cnt;

            if (cnt > 1)

            {

                multi = true;

                break;

            }

            else

            {

                vis[i] = 1;

                first = i;

            }

        }

        if (cnt == 0) return -1;

        for (i = 0; i < n; ++i) if (g[first][i])

            --tmp[i];

        if (multi == false)

            ans[c] = first+'A';

        ++c;

     }

     if (multi == true) return 1;

     ans[c] = 0;

    return 0;

}



void solve(void)

{

    char s[5];

    int t, u, v;

    bool finished = false;

    for (int i = 1; i <= m; ++i)

    {

        scanf("%s", s);

        u = s[0]-'A', v = s[2]-'A';

        if (!g[u][v]) g[u][v] = 1, ++in[v];

        if (finished == false)

        {

            t = topsort();

            if (t == 0)

            {

                printf("Sorted sequence determined after %d relations: %s.\n", i, ans);

                finished = true ;

            }

            else if (t == -1)

            {

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

                finished = true ;

            }

        }

    }

    if (finished == false) printf("Sorted sequence cannot be determined.\n");

}



void init(void)

{

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

    {

        in[i] = 0;

        memset(g[i], 0, sizeof(char)*n);

    }

}



int main()

{    

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

    {

        init();

        solve();

    }

    

    return 0;

}

你可能感兴趣的:(sort)