SDNU1031字母排序(拓扑排序)

第一行——咕咕咕。

第二行感谢csb师哥。

 

先附题目链接SDNUOJ1031

这是一道拓扑排序题,不会的指路博客拓扑排序

说一下思路:

1.统计每个字母的入度(按0~25代表A~Z(每次都需要更新

2.当出现环就说明出现了矛盾

3.如果队列中存在两个及以上可被取出的字符,即入度为0有两个及以上,则为无法确定全部字母的顺序(这句是csb师哥说的

4.如果最后的序列,长度小于n输出矛盾、

再说一下踩过的坑:

1.复环(这个可能没问题

2.getchar(这个也可能没问题

3.局部变量与全局变量(这都能错

4.输入明明有可能是'>',我竟然规定了输入'<'

5.每次输入都进行拓扑排序不是所有输入结束进行判断(这个最重要,我全输入wa了五次都没找到锅在哪儿(再次感谢csb师哥

下附代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <algorithm>
#define ll long long

using namespace std;

string s = "";
int n,m;
int c[27][27];
bool vis[27];
int t[27];

int panduan()
{
    memset(vis,0,sizeof(vis));
    s = "";
    int now[27] = {0};
    for(int i = 0; i < n; ++i)
        now[i] = t[i];
    int q;
    int f = 1;
    for(int i = 0; i < n; ++i)
    {
        int to = 0;
        for(int j = 0; j < n; ++j)
        {
            if(now[j] == 0&&vis[j]==0)
            {
                to++;
                q = j;
            }
        }
        if(to==0)
        {
            return 0;
        }
        if(to>=2)
            f = 2;
        vis[q] = 1;
        for(int j = 0; j < n; ++j)
        {
            if(c[q][j]==1)
            {
                now[j]--;
            }
        }
        s+=q+'A';
    }
    return f;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0&&m==0)
            break;
        char a,b,relation;
        s = "";
        int flag = 0;
        memset(c,0,sizeof(c));
        memset(t,0,sizeof(t));
        int ydr = 0;
        for(int l = 0; l < m; ++l)
        {
            getchar();
            ydr++;
            scanf("%c%c%c",&a,&relation,&b);
            int x = a - 'A';
            int y = b - 'A';
            if(relation == '<')
            {
                if(c[x][y]==0)
                {
                    c[x][y] = 1;
                    t[y]++;
                }
            }
            else if(relation == '>')
            {
                if(c[y][x]==0)
                {
                    c[y][x] = 1;
                    t[x]++;
                }
            }
            int p = panduan();
            if(flag==0)
            {
                if(p == 1)
                {
                    flag = 1;
                    printf("Sorted sequence determined after %d relations: ",ydr);
                    cout<<s<<'.'<<'\n';
                }
                else if(p == 0)
                {
                    flag = 1;
                    printf("Inconsistency found after %d relations.\n",ydr);

                }
            }
        }
        if(flag == 0)
            printf("Sorted sequence cannot be determined.\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值