拓扑排序(topological-sort)

拓扑排序

模板

cpp 复制代码
queue<int> q;
vector<int> v;
for(int i=1;i<=n;++i)
    if(!in[i]) q.push(i);
while(q.size()){
    int x=q.front();
    q.pop();
    v.pb(x); //拓扑序列
    for(int i=head[x];i;i=ne[i]){
        int y=to[i];
        in[y]--;
        if(!in[y]) q.push(y);
    }
}

1.判断是否成环

并查集判 无向图的环,拓扑排序判 有向图的环。

如果拓扑序列点的数量不等于总点数,那么有环。

2.在遍历树时,数出上头需要当前点几次

cpp 复制代码
queue<int> q;
for(int i=1;i<=n;++i)
    if(!in[i]) q.push(i);
vis[n]=1;
while(q.size()){
    int x=q.front();
    q.pop();
    for(int i=head[x];i;i=ne[i]){
        int y=to[i];
        vis[y]+=vis[x];
        in[y]--;
        if(!in[y]) q.push(y);
    }
}
相关推荐
whxnchy14 小时前
UDP多端口负载均衡实战
c++
sheeta199815 小时前
LeetCode 每日一题笔记 日期:2026.05.08 题目:3629. 素数跳跃最小次数
笔记·算法·leetcode
叼烟扛炮15 小时前
C++ 知识点08 类与对象
开发语言·c++·算法·类和对象
米粒115 小时前
力扣算法刷题 Day 63 Bellman_ford 算法
数据库·算法·leetcode
楼田莉子15 小时前
仿Muduo的高并发服务器:Http协议模块
linux·服务器·c++·后端·学习
IT大白鼠1 天前
AIGC性能的关键瓶颈:算力、数据、算法三者如何互相制约?
算法·aigc
tjl521314_211 天前
04C++ 名称空间(Namespace)
开发语言·c++
ximu_polaris1 天前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
白雪茫茫1 天前
监督学习、半监督学习、无监督学习算法详解
python·学习·算法·ai
FengyunSky1 天前
浅析 空间频率响应 SFR 计算
算法