拓扑排序(Topological Sort)

拓扑排序 topologicalSort 拓扑排序 topologicalSort背景知识 ---- 图 (Graph)顶点和边 (vertex and edge)无向图 (Undirected Graph)有向图 (Directed Graph)有向图的degree图中的环基本概念什么是拓扑排序拓扑排序的代码思路 --- 利用广度优先搜索(BFS)拓扑排序的实现时间复杂度拓扑排序的相关问题判断是否存在拓扑排序判断是否仅存一个拓扑排序如何求按最小或最大顺序排列拓扑排序Leetcode Example: 背景知识 ---- 图 (Graph) 顶 阅读详情

0)拓扑排序

原文地址:点击打开链接

拓扑排序是对有向无圈图的顶点的一种排序,这个排序的结果是如果存在一条vi到vj的路径,那么排序中vi在vj的前面。

下图是一个有向无圈图的例子:


在这个有向无圈图中,1,6,5,7,4,2,3;1,6,5,7,2,4,3;这两组都是拓扑排序,我们可以看到这两种排序都满足拓扑排序的要求,比如说1-4的路径,可知1,7,4;1,6,5,4;1,6,7,4;1,6,5,7,4;这些路径的点都按照拓扑排序的要求排列。


1) 简单的拓扑排序算法

下面我们介绍一个简单的拓扑排序算法:

a)先找到一个没有输入边的点,输出这个点,然后去掉与这个点连接的所有边。

b)重复上面的步骤知道输出所有的点。


这里为了编程方便,我们要先定义一个叫做indegree的概念:

indegree: 顶点v包含的边(u,v)的个数。

注意是有向图的v包含的边(u,v)的个数。因此对于上图的点1,它的indegree=0,因为进入点1的边为0,点1的三条边全是指向外的。

所以通过引入indegree概念,上面的简单算法就可以用下面的方式表示

a) 查找indegree为0的点p

b) 对所有与p邻接的点的indegree = indegree -1;

c) 查找indegree为0的点(p除外),然后循环过程

下面是简单的拓扑排序算法的一段伪代码

  1. void TopSort(Graph G)  
  2. {  
  3.     int Num;  
  4.     Vertex V,W;  
  5.     for(Num=0;Num<NumVertex;Num++)  
  6.     {  
  7.         V = FindNewVertexOfDegreeZero();  
  8.         if(V==NotVertex)  
  9.         {  
  10.             Error("Graph has a cycle!");  
  11.             break;  
  12.         }  
  13.         Output[V] = Num;  
  14.         for each W adjacent to V  
  15.             Indegree[W]--;  
  16.     }  
  17. }  


2)  拓扑排序的改进算法
上面的简单算法还是很简单的,也很好理解,那么为什么要改进上面的算法呢?这个主要是因为上面算法的时间复杂度为O(|V|^2)。

首先FindNewVertexOfDegreeZero()函数因为要找到indegree=0的点,所以需要遍历所有的点,因此时间复杂度为O(|V|)。而这个函数需要重复|V|次,因此上面的算法的时间复杂度为O(|V|^2)。因此我们需要做一些改进,来降低运行时间。

可以看到,这里可能能够进行改进的就是FindNewVertexOfDegreeZero()函数。当我们删除一个indegree=0的点后,只有与这个邻接的点的indegree才会减一,其他的点的indegree值不变,因此当我们需要在一次FindNewVertexOfDegreeZero时,不需要遍历所有的点,只需要遍历部分相关连的点就可以。

为了实现上面的思想,我们把indegree=0的点放到一个box中,因此FindNewVertexOfDegreeZero()函数只需要在这个box中寻找就好了。当一个点的indegree=0时,我们就把这个点输入到box中。

算法:

a) 把ndegree=0的点A放到一个Queue中;

b) 把点A出队,然后对所有的与A邻接的点的indegree减一;

c) 把新的ndegree=0的点入队;

d) 重复上面的步骤


伪代码实现:

  1. void TopSort(Graph G)  
  2. {  
  3.     Queue Q;  
  4.     int Num=0;  
  5.     Vertex V,W;  
  6.     Q = CreateQueue(NumVertex);  
  7.     MakeEmpty(Q);  
  8.     while(!IsEmpty(Q))  
  9.     {  
  10.         V = Dequeue(Q);  
  11.         TopNum[V] = ++Num;  
  12.         for each W adjacent to V  
  13.             if(--Indegree[W]==0)  
  14.                 Enqueue(W,Q);  
  15.     }  
  16.     if(Num!=NumVertex)  
  17.         Error("Graph has a cycle!");  
  18.     Free(Q);  
  19. }  

这个方法相当于是以空间换时间,引入了一个Queue。
leetcode刷题笔记-topological sort拓扑排序(DFS) 207.Course Schedule 找环 There are a total ofncourses you have to take, labeled from0ton-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, whi... 阅读详情

相关推荐

拓扑排序(Topological Sorting)算法

拓扑排序(Topological Sorting)在图论中,由一个有向无环图的顶点组成的序列,当且仅当满足下列条件时,称为该图的一个拓扑排序: 每个顶点出现且只出现一次; 若A在序列中排在B的前面,则在图中不存在从B到A的路径。 用顶点表示活动,用弧表示活动之间的优先关系,这样的有向图为顶点表示活动的网,称为AOV网(Activity On Vertex Network)。 另外,AOV网是一种有

贱贱的梦想 4124

拓扑排序

拓扑排序 一、拓扑排序的定义: 先引用一段百度百科上对于拓扑排序的定义: 对一个有向无环图 ( Directed Acyclic Graph 简称 DAG ) G 进行拓扑排序,是将 G 中所有顶点排成一个线性序列,使得图中任意一对顶点 u 和 v ,若边 < u , v > ∈ E ( G ),则 u 在线性序列中出现在 v 之前。通常,这样的线性序列称为满足拓扑次序 ( Topological Order ) 的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这

chenweiye1的博客 6万+

使用boost::topological_sort进行拓扑排序的示例程序

拓扑排序是一种对有向无环图(DAG)进行排序的算法,其中节点按照依赖关系进行排序,确保在排序结果中,任何一个节点都在其依赖节点之后。Boost库提供了一个方便的函数boost::topological_sort,可以帮助我们执行拓扑排序。通过使用Boost库提供的函数,我们可以轻松地进行拓扑排序,从而解决依赖关系排序的问题。然后,我们使用枚举类型定义了图的顶点,这里我们定义了5个顶点A、B、C、D和E。最后,我们打印排序结果,这里使用了反向迭代器,以便按照正确的排序顺序输出结果。来存储排序结果,然后使用。

DevProZ的博客 195

拓扑排序详解

古人学问无遗力 少壮功夫老始成

qq_56012214的博客 2万+

JavaScript:实现Topological Sort拓扑排序算法(附完整源码)

JavaScript:实现Topological Sort拓扑排序算法(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 579

基于大疆TSDK与Pix4D的热红外数据工程化处理:从RJPG到温度正射影像的完整工作流

本文详细介绍了基于大疆TSDK与Pix4D的热红外数据工程化处理完整工作流。通过Python脚本自动化解析RJPG格式的热红外图像,提取并转换其中的原始辐射数据为包含真实温度信息的TIFF文件,再结合Pix4Dmapper进行批量拼接,最终生成可直接用于GIS分析的温度正射影像图。该流程解决了手动处理效率低下、参数校准复杂等难题,实现了从原始数据到定量分析成果的高效、准确、可重复生产。

weixin_29161785的博客 375

拓扑排序 Topological Sort

文章目录AOV网介绍拓扑排序拓扑排序算法举栗 AOV网介绍 在一个表示工程的有向图中,用顶点表示活动,用弧表示活动之间的优先关系,这样的有向图为顶点表示活动的网,我们称AOV网(Activity On Vertex Network). 如图: 设G(V,E)是一个具有n个顶点的有向图,V中的顶点序列v1,v2,…vn,满足若从顶点vi到vj有一条路径,则在顶点序列中顶点vi必在顶点vj之间。则我们称这样的顶点序列为一个拓扑序列。 拓扑排序 拓扑排序,就是对一个有向图构造拓扑序列的过程。 构造时,会出现两种

qq_52109814的博客 784

逆向实战:拼多多anti-content加密参数的全链路解析与动态对抗策略

本文深入解析了拼多多anti-content加密参数的全链路生成逻辑与动态对抗策略。通过逆向工程实战,详细拆解了包含设备指纹、用户行为采集和动态密钥生成在内的12个关键环节,并提供了可持续对抗的精准模拟方案和自动化更新机制,帮助开发者有效应对拼多多的反爬体系。

weixin_30687051的博客 160

Topological Sort拓扑排序

在计算机科学中有很多问题的本质就是一个排序的问题,排序中最简单直接的形式就是对一堆数字进行排序。但是还有一些情况和数字没有关系的,这些情况下也需要进行一定的排序。比如说,穿衣服的过程,你首先需要穿上内衣,然后才能穿上外套,继而才能带上手表等佩戴物。这些事情都是需要排序的,但是这些事情的排序就不是简单的数字排序,因为这里面压根就没有数字。 那么面对这样的问题,我们怎么排序呢?最容易想到的问题就是使用

Android Fans 3713

《无人驾驶车辆模型预测控制》(第二版)第四章详细学习——算法部分

根据代码进行的“MPC跟踪直线和圆算法”的详细推导学习记录。

Fengdf666的博客 5015

Vc出现不能连接到一个或多个 vCenter server 系统:http://vcenter-vx.utibet.edu.cn:443/sdk

问题描述: 解决办法: esxi6.7的bug 第一种通过升级系统来解决问题 第二种是通过删除数据来解决 第一步:进入到esxi的shell 第二步查看其中的服务开启状态 第二步 df -h 第三步 /opt/vmware/vpostgres/current/bin/psql -d VCDB -U postgres 第四步 SELECT nspname || '.' || relname AS "relation", pg_size_pretty(pg_total_relation_size(C.oi

m0_49328536的博客 9900

拓扑排序 - Topological Sort

有向图的拓扑排序是它的顶点的线性排序,比如任意 边 uv 对于 它的顶点 u 和 顶点 v, u v按照 u 在前 v在后的顺序排序。 注意: 只有 有向无环图 (DAG) 才有拓扑排序, 如果一个图 是有环 的图那么它不存在拓扑排序。 在现实生活中, 拓扑排序能被用于以下场景。 比如任意顶点都是要完成的任务,并且每个边 都是 完成一个任务才能继续完成下一个任务的 一种限制。 所以在这

YtdxYHZ的专栏 809

从稀疏表示到低秩表示(一)

确定研究方向后一直在狂补理论,最近看了一些文章,有了些想法,顺便也总结了representation系列的文章,由于我刚接触,可能会有些不足,愿大家共同指正。 从稀疏表示到低秩表示系列文章包括如下内容: 一、 sparse representation 二、 一、 sparse representation 1  sparsity  一个线性表示解决的问题如下图所示:

彼岸花 3万+

拓扑排序(topological sort)

扑排序,是对有向无环图(Directed Acylic Graph , DAG )进行的一种操作,这种操作是将DAG中的所有顶点排成一个线性序列,使得图中的任意一对顶点u,v满足如下条件: 若边(u,v)∈E(G),则u在最终的线性序列中出现在v的前面 拓扑排序描述了一种逻辑先后关系。 当然,拓扑排序往往不会只有一种,通过DFS,我们可以求得拓扑排序。 拓扑排序的思

ninesun的博客 934

drm 之modes

#define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <time.h&...

u012794472的专栏 3716

Visual Studio调试技巧与实用方法总结(实战经验分享)

本文根据多年的项目实战经验,详细介绍一些Visual Studio常用的高效调试手段与技巧。

dvlinker的技术专栏 3万+

拓扑排序Topological Sort

拓扑排序用于有向无环图(DAG),作用是给出一个序列,使得任何一条边总是起点比终点在序列中出现的位置靠前拓扑排序原理是每次找到入度为0的点,把它放进拓扑排序的序列中,然后把这个点和这个点引出的边全部删掉(当然,一个图的拓扑序不是唯一的,只要起到功效就可以了)这个排序在没碰见它的题之前就会觉得这毫无用处,举个例子,拓扑排序可以用于动态规划动态规划需要满足些什么条件?无后效性而拓扑排序像什么?过关斩将,“给出一个序列,使得任何一条边总是起点比终点在序列中出现的位置靠前”这句话恰好是无后效性的体现。

gzr_csdn的博客 285

海洋捕食者算法(MPA)详解:从海洋生态智慧到高性能优化

摘要: 海洋捕食者算法(MPA)是一种基于海洋生态觅食行为的元启发式优化算法,模拟捕食者(如鲨鱼)的布朗运动和莱维飞行策略进行全局与局部搜索。算法分为三阶段:高速比阶段(全局探索)、单位速度比阶段(平衡搜索)和低速比阶段(局部开发),通过精英矩阵和FADs效应(概率扰动)避免早熟收敛。MPA具有参数少、收敛快、寻优能力强等特点,适用于复杂优化问题,其数学模型将生物行为转化为随机游走与自适应策略,并通过收敛因子动态调整探索-开发平衡。实验表明,MPA在多个基准问题上表现优异。

qq_42212808的博客 273

拓扑排序 Graph: Topological Sort

文章目录DefinitionDAG 有向无环图AOV 网Topological Sort 拓扑排序Performance Definition DAG 有向无环图 若一个有向图中不存在环,则称为有向无环图(DAG,Directed-Acyclic-Graph) AOV 网 若用有向无环图表示一个工程,其顶点表示活动,用有向边 <Vi,Vj><V_{i},V_{j}><...

还是应该要努力的(12点前睡觉!!!!! 513

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

上一篇: 非常可乐(BFS)
下一篇: 6-16 Topological Sort(25 point(s))
Guuuuuu老师儿
博客等级 码龄9年 259粉丝 718原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值