搜索与图论-拓扑序列

为什么记录呢

因为不记录全忘了

虽然记了也不一定会看

  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;
}
相关推荐
LYFlied2 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠2 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr8733 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu5 小时前
整数数组匹配
数据结构·c++·算法
smj2302_796826525 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied6 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-6 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄6 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳7 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang7 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽