图论(算法竞赛、蓝桥杯)--拓扑排序

1、B站视频链接:D01 拓扑排序_哔哩哔哩_bilibili

cpp 复制代码
#include <bits/stdc++.h> 
using namespace std;
const int N=100010;
int n,m,a,b;
vector<int> e[N],tp;
int din[N];
bool topsort(){
	queue<int> q;
	for(int i=1;i<=n;i++){
		if(din[i]==0)q.push(i);
	}
	while(q.size()){
		int x=q.front();q.pop();
		tp.push_back(x);
		for(auto y:e[x]){
			if(--din[y]==0)q.push(y);
		}
	}
	return tp.size()==n;
}
int main(){
	cin>>n>>m;
	for(int i=0;i<m;i++){
		cin>>a>>b;
		e[a].push_back(b);//a到b的有向边
		din[b]++;//入度加一 
	}
	if(!topsort())puts("-1");
	else for(auto x:tp)printf("%d ",x);
	return 0;
}
cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 100010;
int n,m,a,b;
vector<int> e[N], tp;
int c[N]; //染色数组

bool dfs(int x){
  c[x] = -1;
  for(int y : e[x]){
    if(c[y]<0)return 0; //有环 
    else if(!c[y])
      if(!dfs(y))return 0;
  }
  c[x] = 1;
  tp.push_back(x);
  return 1;
}
bool toposort(){
  memset(c, 0, sizeof(c));
  for(int x = 1; x <= n; x++)
    if(!c[x])
      if(!dfs(x))return 0;
  reverse(tp.begin(),tp.end());
  return 1;
}
int main(){
  cin >> n >> m;
  for(int i=0; i<m; i++){
    cin >> a >> b;
    e[a].push_back(b);
  }
  if(!toposort()) puts("-1");
  else 
    for(int x:tp)printf("%d ",x);
  return 0;
}
相关推荐
Shan120510 小时前
无向图的Hierholzer算法流程(二)
算法
gihigo199810 小时前
基于蒙特卡洛的异常值剔除(RANSAC + MC置信区间)—MATLAB实现
开发语言·算法·matlab
Asize11 小时前
数组数据结构底层:从灵活到陷阱
前端·javascript·算法
hairenwangmiao11 小时前
B4041 [GESP202409 四级] 区间排序
算法·排序
人道领域11 小时前
【LeetCode刷题日记】47.全排列Ⅱ
java·开发语言·算法·leetcode
漂流瓶jz12 小时前
UVA-1606 两亲性分子 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·向量·aoapc·算法竞赛入门经典·atan2·浮点
Navigator_Z12 小时前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
不会就选b12 小时前
算法日常・每日刷题--<二分查找>1
算法
Chen_harmony12 小时前
二、顺序表
数据结构
「維他檸檬茶」12 小时前
大模型算法学习2026.6.13
学习·算法