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

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;
}
相关推荐
山北雨夜漫步43 分钟前
机器学习 Day14 XGboost(极端梯度提升树)算法
人工智能·算法·机器学习
到底怎么取名字不会重复1 小时前
Day10——LeetCode15&560
c++·算法·leetcode·哈希算法·散列表
chuxinweihui1 小时前
数据结构——二叉树,堆
c语言·开发语言·数据结构·学习·算法·链表
freexyn2 小时前
Matlab自学笔记五十一:(推荐)输入参数的数量和可变数量的输入
笔记·算法·matlab
陈大大陈2 小时前
基于 C++ 的用户认证系统开发:从注册登录到Redis 缓存优化
java·linux·开发语言·数据结构·c++·算法·缓存
看到我,请让我去学习2 小时前
C语言基础(day0424)
c语言·开发语言·数据结构
数据分析螺丝钉2 小时前
LeetCode 252 会议室 III(Meeting Rooms III)题解与模拟面试
算法·leetcode·职场和发展
小李独爱秋2 小时前
动态哈希映射深度指南:从基础到高阶实现与优化
数据结构·算法·哈希算法
猫猫头有亿点炸2 小时前
C语言斐波拉契数列2.0
c语言·开发语言·算法
写个博客2 小时前
代码随想录算法训练营第二十六天
算法