拓扑排序

拓扑排序就是在一个关系网络中遍历所得出的一个路径,这个网络就叫做AOV网。

拓扑排序即是对一个有向无环图里顶点之间的先后关系的表达。

这个有什么用呢,它就像图的遍历一样,不会单个地出题,但是会和其他的题联系起来。

例题:

给你一个有n个点,m条边的图,输出这个图的拓扑序。

我们可以建立一个空队列,然后将所有入度为零的点入队,然后从队列中取出一个点,将与这个点相连的所有点的入度减一,如果这些点中又有入度为零的点就再把他入队,直到队列为空。

代码:

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
queue<int>q;
int in_degree[100010],tot,lin[100010],n,m;
struct cym{
    int from,to,next;
}e[100010];
void add(int x,int y)
{
    e[++tot].from=x;
    e[tot].to=y;
    e[tot].next=lin[x];
    lin[x]=tot;
    in_degree[y]++;
}
void tupusort()
{
    for(int i=1;i<=n;i++)
      if(!in_degree[i])
        q.push(i);
    while(!q.empty())
    {
     int cur=q.front();
     q.pop();
     cout<<cur<<" ";    
     for(int i=lin[cur];i;i=e[i].next)
     {
         in_degree[e[i].to]--;
         if(!in_degree[e[i].to])
         q.push(e[i].to);
     }
    }    
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y);
    }
    tupusort();
}

 

posted @ 2018-06-23 14:46  DAGGGGGGGGGGGG  阅读(127)  评论(0编辑  收藏  举报