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

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;
}
相关推荐
sx24369412 分钟前
day21:零基础学嵌入式之数据结构
数据结构
ai.Neo29 分钟前
牛客网NC22157:牛牛学数列2
数据结构·c++·算法
Nobkins1 小时前
2023CCPC河南省赛暨河南邀请赛个人补题ABEFGHK
开发语言·数据结构·c++·算法·图论
王RuaRua1 小时前
[数据结构]7. 堆-Heap
c语言·数据结构·算法·链表
朱剑君2 小时前
第八天——贪心算法——队列重构问题
算法·贪心算法·重构
仙人掌_lz2 小时前
深度理解用于多智能体强化学习的单调价值函数分解QMIX算法:基于python从零实现
python·算法·强化学习·rl·价值函数
riri19192 小时前
算法分析:蛮力法
数据结构·算法
Christo32 小时前
关于在深度聚类中Representation Collapse现象
人工智能·深度学习·算法·机器学习·数据挖掘·embedding·聚类
摄殓永恒2 小时前
猫咪几岁
数据结构·c++·算法
机器学习之心2 小时前
分类预测 | Matlab实现ABC-Transformer人工蜂群算法优化编码器多特征分类预测/故障诊断Matlab实现
算法·matlab·分类