Loading

拓扑排序

ll ans[100] ,cnt; //拓扑序列及其元素个数
ll deg[100];       //所有点的入度

void topsort()
{
    queue<ll> q;
    for (int i = 1; i <= n; ++i)
        if (deg[i] == 0) //寻找最开始入度就为0的点
            q.push(i);   //入队

    while (!q.empty())
    {
        ll x = q.front();
        q.pop();
        ans[++cnt] = x; //把队首的元素放进拓扑序列
        for (int i = head[x]; i; i = t[i].nxt)
        {
            ll y = t[i].to;    //寻找邻边
            if (--deg[y] == 0) //邻边的入度-1,并且判断减后的入度是否为0
                q.push(y);     //如果为0就入队
        }
    }
}

int main()
{
    n = read();
    m = read(); //点,边
    for (int i = 1; i <= m; ++i)
    {
        ll x = read(), y = read();
        add(x, y);
        deg[v]++; //入度++
    }

    topsort(); //拓扑排序

    if (cnt < n) //拓扑序列的元素个数小于点数,说明有环
        puts("有环");
    else
        puts("无环");

    for (int i = 1; i <= cnt; ++i)
        printf("%lld ", ans[i]); //输出拓扑序列

    return 0;
}
posted @ 2021-06-29 10:41  EdisonBa  阅读(40)  评论(0编辑  收藏  举报