拓扑排序

【题目地址】POJ1094

【题目大意】题目意思比较容易理解,我就不在这里多说了。

【题目分析】该题需要利用拓扑排序进行处理

【代码】

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stack>
#define mem(x)  memset((x),0,sizeof((x)))
const int N=30;
using namespace std;
int graph[N][N];
int indegree[N];
int list[N];

int toposort(int n) {
    int in[N];
    memcpy(in,indegree,sizeof(indegree)); //复制入度数组,以免对主函数中的indegree有影响
    stack<int> s;
    int i;
    for(i=0; i<n; i++)
        if(!in[i])
            s.push(i);//所有入度为0的点入栈,如果这些点多于1的话,序列不确定
    int flag=0;
    int t,j=0;
    while(!s.empty()) {
        if(s.size()>1)
            flag=1;    //序列不确定
        t=s.top();
        s.pop();
        list[j++]=t;   //记录出栈的数字
        for(i=0; i<n; i++)
            if(graph[t][i])
                if(--in[i]==0)
                    s.push(i);//入度为0的点入栈
    }
    if(j!=n)//不能拓扑排序,即有环
        return 1;
    else if(flag==1)//有多种排序方式,不能唯一确定
        return 2;
    return 0;//序列能够被唯一确定
}

int main()
{
    freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n,m;
    int determined,Inconsistency;
    int res;
    char a,b;

    while(scanf("%d%d",&n,&m) != EOF && n+m){
        getchar();

        mem(graph);
        mem(indegree);
        determined = 0;
        Inconsistency = 0;

        for(int i = 1; i <= m; i++){
            scanf("%c<%c",&a,&b);
            getchar();

            if(!determined && !Inconsistency){
                if(graph[b-'A'][a-'A'] == 1){
                    Inconsistency = 1;
                    printf("Inconsistency found after %d relations.\n",i);
                    continue;
                }
                if(graph[a-'A'][b-'A'] == 0){
                    graph[a-'A'][b-'A'] = 1;
                    indegree[b-'A']++;
                }

                res = toposort(n);

                if(res == 0){
                    printf("Sorted sequence determined after %d relations: ",i);
                    for(int j = 0; j < n; j++){
                        printf("%c",list[j] + 'A');
                    }
                    printf(".\n");

                    determined = 1;
                }
                else if(res == 1){
                    printf("Inconsistency found after %d relations.\n",i);
                    Inconsistency = 1;
                }
            }
        }
        if(!determined && !Inconsistency){
            printf("Sorted sequence cannot be determined.\n");
        }
    }
    return 0;
}

【注】以上代码参考了博主 pushing my way 关于该题的解题代码

【后记】toposort函数我还是没怎么看懂


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值