AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

AcWing 848. 有向图的拓扑序列    原题链接    简单

作者: 作者的头像   zxq0408 ,  2023-03-19 12:48:44 ,  所有人可见 ,  阅读 17


0


算法思路

数组模拟队列

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100010;
int n, m;
int e[N], ne[N], h[N], idx;
int q[N];
int d[N];  //d[i]存储点i的入度

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

//判断是否有拓扑排序
bool topsort()
{
    int hh = 0, tt = -1;
    for(int i = 1; i <= n; i ++)
        if(!d[i])
            q[++ tt] = i;

    while(hh <= tt)
    {
        int t = q[hh ++];

        for(int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(--d[j] == 0)
                q[++ tt] = j;
        }
    }
    //如果所有点都入队了,说明存在拓扑序列;否则不存在拓扑序列。
    return tt == n-1;
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof(h));// 初始化
    while(m--)
    {
        int x, y;
        cin >> x >> y;
        add(x, y);
        d[y] ++;  // y的入度+1
    }
    if(!topsort()) cout << "-1" <<endl;
    else
    {
        for(int i = 0; i < n; i ++) cout << q[i] <<" ";
        cout<<endl;
    }
    return 0;
}

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息