【模板】拓扑排序

 

记住了l,r

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
struct edge{
    int to, nxt;
}e[maxn];
int head[maxn], cnt;
int n, m, x, y, q[maxn], r = -1, d[maxn], l;

void add(int u, int v)
{
    e[++cnt].to = v;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}

int topsort()
{
    for(int i = 1; i <= n; i++)
        if(!d[i]) q[++r] = i;
    while(l <= r)
    {
        int now = q[l++];
        for(int i = head[now]; i; i = e[i].nxt)
        {
            if(--d[e[i].to] == 0)
                q[++r] = e[i].to;
        }
    }
    if(r == n-1) return 1;
    else return 0;
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        cin >> x >> y;
        add(x, y);
        d[y]++;
    }
    if(topsort())
    {
        for(int i = 0; i < n; i++)
            cout << q[i] << " " ;
    }
    else cout << "-1";
    return 0;
}

 

 

 

posted @ 2019-11-12 22:30  ATKevin  阅读(197)  评论(0)    收藏  举报