搜索与图论-拓扑序列

为什么记录呢

因为不记录全忘了

虽然记了也不一定会看

  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;
}
相关推荐
技术专家6 分钟前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet28 分钟前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp43 分钟前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium2 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5633 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮4 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11014 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆4 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法
汀、人工智能5 小时前
[特殊字符] 第86课:最大正方形
数据结构·算法·数据库架构·图论·bfs·最大正方形
hetao17338375 小时前
2026-04-12~14 hetao1733837 的刷题记录
c++·算法