拓朴排序详解

//vector 
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <cmath>
#include <iomanip>
#include <utility>
#include <vector>

using namespace std;

#define _for(i, a, b) for(int i = (a); i < (b); ++i)
#define _rep(i, a, b) for(int i = (a) - 1; i >= (b); --i)

typedef long long ll;
typedef unsigned long long ull;

const int N = 1e5 + 11;

int n, m, x, y;
int in[N];//入度 
vector<int> edge[N];

void toposort()
{

    queue<int> q;//队列 
    vector<int> ans;
    ans.clear();
    //memset(in, 0, sizeof in);

    //q.push();
    //q.front();
    //q.pop();
    //q.empty();

    _for(i, 1, n + 1) if(in[i] == 0) q.push(i);//所有入度为0的点 

    while(!q.empty())//队列不为空 
    {
        int p = q.front();//取队头 
        q.pop();//删队头 
        ans.push_back(p);

        //_for(i, 0, edge[p].size())
        for(int i=0;i<edge[p].size();++i)
        {
            int u = edge[p][i];//
            in[u]--;
            if(in[u] == 0) q.push(u);
        }
    }

    if(ans.size() == n)
    {
        _for(i, 0, ans.size()) cout << ans[i] << " ";
        cout << '\n';
    }
    else cout << -1 << '\n';
    return;
}

int main()
{
    //std::ios::sync_with_stdio(false);
    //std::cin.tie(0);

    cin >> n >> m;
    _for(i, 0, m)
    {
        cin >> x >> y;
        edge[x].push_back(y);
        in[y]++;
    }

    toposort();
    return 0;
}


//输入:
//3 3
//1 2
//2 3
//1 3
//输出: 
//1 2 3 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值