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

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;
}
相关推荐
Gyoku Mint2 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
葫三生3 小时前
如何评价《论三生原理》在科技界的地位?
人工智能·算法·机器学习·数学建模·量子计算
拓端研究室5 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
wwer1425263635 小时前
数学建模_图论
数学建模·图论
随缘而动,随遇而安7 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
IT古董8 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
水木兰亭10 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
Jess0711 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁11 小时前
选择排序算法详解
数据结构·算法·排序算法
xindafu11 小时前
代码随想录算法训练营第四十二天|动态规划part9
算法·动态规划