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

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;
}
相关推荐
远远远远子1 分钟前
C++-- 内存管理
c++·算法
sprintzer17 分钟前
10.6-10.15力扣模拟刷题
算法·leetcode·职场和发展
徐子童18 分钟前
算法---队列+宽搜
算法··队列·层序遍历
一念&22 分钟前
每日一个C语言知识:C 数组
c语言·开发语言·算法
小年糕是糕手24 分钟前
【数据结构】单链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表
咸鱼爱学习1 小时前
【题解】B2613【深基1.习5】打字速度
数据结构·c++·算法
阿林学习计算机1 小时前
AVL树的实现
数据结构
whm27772 小时前
Visual Basic 值传递与地址传递
java·开发语言·数据结构
立志成为大牛的小牛2 小时前
数据结构——二十二、并查集(王道408)
c语言·数据结构·笔记·学习·考研
云青黛2 小时前
轮廓系数(一个异型簇的分类标准)
人工智能·算法·机器学习