搜索与图论-拓扑序列

为什么记录呢

因为不记录全忘了

虽然记了也不一定会看

  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;
}
相关推荐
C雨后彩虹1 天前
任务最优调度
java·数据结构·算法·华为·面试
少林码僧1 天前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
钱彬 (Qian Bin)1 天前
项目实践15—全球证件智能识别系统(切换为Qwen3-VL-8B-Instruct图文多模态大模型)
人工智能·算法·机器学习·多模态·全球证件识别
Niuguangshuo1 天前
EM算法详解:解密“鸡生蛋“的机器学习困局
算法·机器学习·概率论
a3158238061 天前
Android 大图显示策略优化显示(一)
android·算法·图片加载·大图片
一条大祥脚1 天前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
鲨莎分不晴1 天前
反向传播的数学本质:链式法则与动态规划的完美共舞
算法·动态规划
sonadorje1 天前
逻辑回归中的条件概率
算法·机器学习·逻辑回归
cici158741 天前
基于Pan-Tompkins算法的ECG信号HRV提取方案
算法
McGrady-1751 天前
拓扑导航 vs 几何导航的具体实现位置
算法