搜索与图论-拓扑序列

为什么记录呢

因为不记录全忘了

虽然记了也不一定会看

  1. 有向无环图一定有拓扑序列
  2. 邮箱无环图 - 拓扑图
  1. 入度为0的点作为起点
  2. 入度为0的点入队列
  3. 枚举出边 t->j
  4. 删掉当前边,t->j . j的入度减1
  5. 判断j的入度是否为0,来判断是否加入队列
  1. 有环: 不存在入度为0的点
cpp 复制代码
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>

using namespace std;

const int maxn = 100010;

int h[maxn], e[maxn], ne[maxn], idx;

int q[maxn],d[maxn];

int n;

int hh = 0, tt = -1;

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

bool topsort(){
    
    while(hh <= tt){
        int t = q[hh++];
        for(int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            d[j]--;
            if(d[j] == 0){
                q[++tt] = j;
                // cout<<"j: "<< j << " "; 
            }
        }
    }
    // cout<<"tt " << tt << "n-1 "<< n-1 << '\n';
    return tt == n-1;
    
}

int main(){
    int m,a,b;
    
    memset(h , -1, sizeof h);
    cin >> n >> m;
    for(int i = 0; i < m; i++){
        cin>>a>>b;
        add(a,b);
        // cout<<"b  "<< b << " ";
        d[b]++;
        
    }
    
    
    for(int i = 1; i <= n; i++){
        if(d[i] == 0){
            // cout<<"i: " << i<<'\n';
            q[++tt] = i;
        }
    }
    
    if(topsort()){
        for(int i = 0; i < n; i++){
            cout<<q[i] << " ";
        }
        
    }else cout<<-1<< '\n';
    
    return 0;
}
相关推荐
西工程小巴4 分钟前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程16 分钟前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit22 分钟前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
百度Geek说2 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven2 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven2 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试
CoovallyAIHub2 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·计算机视觉
kyle~3 小时前
OpenCV---特征检测算法(ORB,Oriented FAST and Rotated BRIEF)
人工智能·opencv·算法
初学小刘3 小时前
决策树:机器学习中的强大工具
算法·决策树·机器学习
山顶风景独好3 小时前
【Leetcode】随笔
数据结构·算法·leetcode