搜索与图论-拓扑序列

为什么记录呢

因为不记录全忘了

虽然记了也不一定会看

  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;
}
相关推荐
米粒118 分钟前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___1 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
漫随流水2 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub5 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub5 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub5 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki6 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic6 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展
荣光属于凯撒6 小时前
P2176 [USACO11DEC] RoadBlock S / [USACO14FEB] Roadblock G/S
算法·图论