拓扑排序(访问层数,判断有无环)

本文介绍了一种通过队列和集合来检测图中是否存在环,并利用队列记录访问层数确定最长链长度的算法。应用在排序问题上,主要针对字符串操作的图结构。通过实例展示了如何在C++中实现这一过程,以确定有向图的有序序列。
摘要由CSDN通过智能技术生成

通过看加入队列的元素个数和总元素个数判断有无环

通过记录队列访问层数得到最长链的长度

排序 - 洛谷 

#include<bits/stdc++.h>
using namespace std;
int read() {
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
    while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
    return x*f;
}
void write(int x) {
     if(x<0) putchar('-'),x=-x;
     if(x>9) write(x/10);
     putchar(x%10+'0');
}
int n,m,uu,vv,sum;
string kk;
struct edge{
    int from,to,nex;
}e[650];
int head[30],in[30];
void add(int kk)
{
    e[kk]=(edge){uu,vv,head[uu]};
    head[uu]=kk;
}
struct one{
    int x,fl;
};
set<int>s;
int f=0;
queue<one>q;
queue<int>q1;
void solve()
{
    for(int i=1;i<=26;++i)
    {
        if(in[i]==0&&s.count(i))
        {
            q1.push(i);
            printf("%c",'A'+i-1);
        }
    }
    int now;
    while(!q1.empty())
    {
        now=q1.front();
        q1.pop();
        for(int i=head[now];i!=-1;i=e[i].nex)
        {
            in[e[i].to]--;
            if(in[e[i].to]==0)
            {
                q1.push(e[i].to);
                printf("%c",'A'+e[i].to-1);
            }
        }
    }
    
}
void topu(int pp)
{
    while(!q.empty())
        q.pop();
    int summ=0;
    int ans=0;
    one now;
    int fln;
    int inn[30];
    for(int i=1;i<=26;++i)
    {
        inn[i]=in[i];
        if(in[i]==0&&s.count(i))
        {
            q.push((one){i,1});
            summ++;
            ans=1;
        }
    }
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        fln=now.fl;
        for(int i=head[now.x];i!=-1;i=e[i].nex)
        {
            inn[e[i].to]--;
            if(inn[e[i].to]==0)
            {
                summ++;
                q.push((one){e[i].to,fln+1});
                ans=max(ans,fln+1);
            }
        }
    }
    if(summ!=sum)
    {
        f=1;
        printf("Inconsistency found after %d relations.",pp);
    }
    else if(ans==n)
    {
        f=1;
        printf("Sorted sequence determined after %d relations: ",pp);
        solve();
        printf(".");
    }
}
int main ()
{
    n=read(),m=read();
    memset(head,-1,sizeof(head));
    for(int i=1;i<=m;++i)
    {
        cin>>kk;
        uu=kk[0]-'A'+1;
        vv=kk[2]-'A'+1;
        add(i);
        s.insert(uu);
        s.insert(vv);
        sum=s.size();
        in[vv]++;
        if(!f)
            topu(i);
    }
    if(!f)
    {
        printf("Sorted sequence cannot be determined.");
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值