poj1094拓扑排序

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
#define f puts("here")

using namespace std;
int dp[30][30];
char str[5];
int n, m;
int rdu[30];
char s[30];

int sign;
/*
有不明白的可以给我留言 评论
本题特点, 输入狗血,
所用算法, 拓扑排序
*/
int tuopu()
{
    bool flag = true;
    int i, j, k;
    memset(rdu, 0, sizeof(rdu));
    memset(s, '\0', sizeof(s));
    for(i = 1; i <= n; i++) {

        for(j = 1; j <= n; j++) {

            if(dp[i][j])
                rdu[j]++;
        }
    }
    for(i = 1; i <= n; i++) {
        k = 0;
        for(j = 1; j <= n; j++) {

            if(rdu[j] == 0)
            {
                if(k == 0)
                    k = j;
                else
                    flag = false;
            }
        }
        if(k == 0) //形成环了,
            {
                return 0;
            }
            rdu[k] = -1;//将与其有关的入度剪去;
            s[i-1] = 'A' + k -1;
            for(int j = 1; j <= n; j++)
                if(dp[k][j])
                rdu[j]--;
        }
    if(flag) return 1;
    else
        return 2;
}
int main()
{
    while(scanf("%d%d", &n, &m), n+m)
    {

        memset(dp, 0, sizeof(dp));
        int sign = 0;
        for(int i = 1; i <= m; i++)
        {
            scanf("%s", str);
            dp[str[0] - 'A' + 1][str[2]-'A' + 1] = 1;
            if(sign)  continue;
            int result = tuopu();
            if(result==1)
            {
                printf("Sorted sequence determined after %d relations: %s.\n",i,s);
                sign = 1;
            }
            if(result==0)
            {
                printf("Inconsistency found after %d relations.\n",i);
               sign = 1;
            }
        }
        if(!sign) printf("Sorted sequence cannot be determined.\n");
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值