拓扑排序

简介: 有很多任务是按照先后顺序完成的,必须把前面的所有任务完成,才可以做下一个任务。

利用 入读 来表示前面还有多少个任务没有完成,当入度为0,就完成这个任务。

小工具: 优先队列。(优先队列不是动态的,是把每次加入的元素当成一个单独的东西)

代码:

#include <bits/stdc++.h>
using namespace std;
#define M 100005
#define ri register int
 
int n,m;
int du[M];
vector <int> p[M];
struct cmp{
    bool operator ()(const int &a,const int &b)const
    {
         return a>b;
         
    }
};
priority_queue <int,vector<int>,cmp> q;
int num,ot[M],trmp;
 
void ybh()
{
    while(!q.empty())
    {
        int a=q.top();
        q.pop();
        num++;
        ot[++trmp]=a;
        for(ri i=0;i<p[a].size();i++)
        {
            du[p[a][i]]--;
            if(!du[p[a][i]])
            q.push(p[a][i]);
        }
    }
     
}
 
int main(){
    scanf("%d%d",&n,&m);
    for(ri i=1;i<=m;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        p[a].push_back(b);
        du[b]++;
    }
    for(ri i=1;i<=n;i++)
    {
        if(!du[i])
        q.push(i);
    }
    ybh();
    if(num==n)
    {
        for(ri i=1;i<=n;i++)
        {
            printf("%d ",ot[i]);
        }
    }
    else
    {
        printf("no solution");
    }
    return 0;
     
}
拓扑排序

栗子:

原文地址:https://www.cnblogs.com/Lamboofhome/p/15449009.html