zoukankan      html  css  js  c++  java
  • 拓扑排序(模板)

    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;
    int n, m;
    const int N=1e5+10;
    vector<int> out[N];      //入度记录
    int in[N];    //出度记录
    vector<int>ret;
    queue<int> q;
    int topsort()
    {
        while (!q.empty())
        {
            int idx = q.front();
            q.pop();
            ret.push_back(idx);
            //抹掉这个点的所有出度边 与入度计数
            int _size=out[idx].size();
            for (int i=0; i<_size; i++)
            {
                int e=out[idx][i];
                in[e]--; //该点入度减1
                if (in[e] == 0)
                {
                    q.push(e);
                }
            }
        }
    }
    int main()
    {
        cin >> n >> m;
        for (int i = 0; i < m; i++){
            int start;
            int end;
            cin >> start >> end;
            in[end]++;
            out[start].push_back(end);
        }
        for (int i = 1; i <= n; i++){
            //找到第一个入度为0的点
            if (in[i] == 0){
                q.push(i);
            }
        }
        topsort();
        int _size=ret.size();
        if(_size==n){
            for(int i=0; i<_size; i++)
                cout<<ret[i]<<" ";
        }
        else
            cout<<"-1"<<endl;
    
    
        return 0;
    }
    /*3 3
    1 2
    2 3
    1 3*/
    View Code
  • 相关阅读:
    pat甲级1013
    二分查找
    pat甲级1012
    win10 + Ubuntu16.04双系统安装
    win10 U盘重装
    win10蓝牙添加设备无法连接
    Android自定义控件总结
    11.粘性控件
    10.侧拉删除
    9.视差特效、回弹动画、overScrollBy
  • 原文地址:https://www.cnblogs.com/sszywq/p/13892899.html
Copyright © 2011-2022 走看看