拓扑排序模板

拓扑排序模板
/*邻接表拓扑排序模板*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=15;//顶点最大数目
struct Arcnode
{
    int to;
    struct Arcnode *next;
};
int n,m;//顶点,边数
Arcnode* List[maxn];//每个顶点的边链表表头指针
int cunt[maxn];//各顶点的入度
char output[100];//输出内容
void Topsort()
{
    int top=-1;
    Arcnode* temp;
    bool sign=false;//判断是否出现有向环
    int pos=0;//output数组的位置
    for(int i=0;i<n;i++)//入队为0入栈
    {
        if(cunt[i]==0)
        {
            cunt[i]=top;
            top=i;
        }
    }
    for(int i=0;i<n;i++)
    {
        if(top==-1)
        {
            sign=true;
            break;
        }
        else
        {
            int j=top;//出栈+遍历
            top=cunt[top];
            pos+=sprintf(output+pos,"%d ",j+1);
            temp=List[j];
            while(temp!=NULL)
            {
                int k=temp->to;
                if(--cunt[k]==0)
                {
                    cunt[k]=top;
                    top=k;
                }
                temp=temp->next;
            }
        }
    }
    if(sign)
        cout<<"Network has a cycle!"<<endl;
    else
    {
        int len=strlen(output);
        output[len-1]=0;
        cout<<output<<endl;
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        if(!(n||m))
            break;
        memset(List,0,sizeof(List));
        memset(cunt,0,sizeof(cunt));
        memset(output,0,sizeof(output));
        Arcnode* temp;
        int u,v;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&u,&v);
            u--;
            v--;
            cunt[v]++;
            temp=new Arcnode;
            temp->to=v;//构造邻接表
            temp->next=NULL;
            if(List[u]==NULL)//边链表没有节点
                List[u]=temp;
            else//边链表有节点
            {
                temp->next=List[u];
                List[u]=temp;
            }
        }
        Topsort();
        for(int i=0;i<n;i++)//释放存储空间
        {
            temp=List[i];
            while(temp!=NULL)
            {
                List[i]=temp->next;
                delete temp;
                temp=List[i];
            }
        }
    }
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值