拓扑排序

#include<bits/stdc++.h>
using namespace std;
int v,e,x,y,indegree[100],ans[100],t=1;
typedef struct ANode
{
    int adjvex;
    struct ANode *next;
}ANode;
struct VNode
{
    int date;
    ANode *first;
}V[100];

typedef struct Stack
{
    int date[100];
    int top;
}Stack;
void InitStack(Stack &S)
{
    S.top=-1;
}
void Push(Stack &S,int n)
{
    S.top++;
    S.date[S.top]=n;
}
int Pop(Stack &S)
{
    int x=S.date[S.top];
    S.top--;
    return x;
}
int Empty(Stack &S)
{
    if(S.top==-1)
        return 1;
    else
        return 0;
    
}

void GreateGrape()//有向图邻接表
{
    cin>>v>>e;
    for(int i=1;i<=v;i++)
    {
        cin>>V[i].date;
        V[i].first=NULL;
    }   
    for(int i=0;i<e;i++)
    {
        cin>>x>>y;
        indegree[y]++;//入度
        ANode *s=new ANode;//插入边链表
        s->adjvex=y;
        s->next=V[x].first;
        V[x].first=s;
    }
}
void TopologicalSort()//拓扑排序
{
    Stack S;
    InitStack(S);
    for(int i=1;i<=v;i++)
        if(!indegree[i])
            Push(S,i);
    while(!Empty(S))
    {
        int x=Pop(S);
        ans[t]=x;
        t++;
        ANode *p;
        p=V[x].first;//p指向vx的第一个邻接表
        while(p!=NULL)//删除顶点以及以它为尾的操作通过弧头顶点的入度减1实现
        {
            int y=p->adjvex;
            indegree[y]--;
            if(!indegree[y])
                Push(S,y);
            p=p->next;
        }
    }
    if(t-1==v)
    {
        cout<<"无回路,拓扑排序为:"<<endl;
        for(int i=1;i<=v;i++)
            cout<<"v"<<ans[i]<<" ";
    }
}
int main()
{
    GreateGrape();
    TopologicalSort();
    return 0;
}
/*
12 16
1 2 3 4 5 6 7 8 9 10 11 12
1 4
1 2
1 3
1 12
4 5
2 3
3 5
3 7
5 7
3 8
9 12
9 10
10 12
9 11
11 6
6 8
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值