[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
首先需要说明的是拓扑排序是针对有向无环图来说的,有向无环图也就是DAG图,顾名思义就是整张图中的边都带有方向而且不存在环。
上面这张图就是一个简单的拓扑图,而下面这张图就不算是一个拓扑图
原因就在于下面这张图存在环B->C->D->B
现在我们知道什么是拓扑图了,下面我来说一下拓扑图对应的拓扑序列。
常见求拓扑序列的方法:
(1)从拓扑图中找到一个入度为0的点
(2)删除入度为0的点及与其相关联的边(相对应的边的另一端的点的入度会减一)
(3)在删边过程中遇到入度为0的点就加入队列
(4)重复上述操作,直到所有的点入度均变为0
容易发现拓扑图对应的拓扑序列不一定是唯一的,因为我们有可能同时找到多个入度为0的点,这个时候先删哪一个都可以,还以上面的图片为例求其拓扑序列:
其中一个拓扑序列对应A->C->B->D->E(下面这个图)
还有一个拓扑序列对应A->B->C->D->E(下面这个图)
如果一个图是连通的,我们可以通过入队的点数来判断图中是否存在环,有向无环图保证了图中的每一个点都能够入队一次,如果图中存在环,那么入队的点数一定小于图中所有点的点数和。
下面我给出拓扑序列核心代码:
void topsort() { queue<int> q; for(int i=1;i<=n;i++) if(!ru[i])
q.push(i);//入度为0的点入队 tt=0; while(q.size()) { int begin=q.top(); q.pop();
st[++tt]=begin;//记录拓扑序列 for(int i=h[begin];i!=-1;i=ne[i]) { int j=e[i];
ru[j]--; if(!ru[j]) q.push(j);//入度为0的点入队 } } }