• 【算法】【图】拓扑排序


    邻接矩阵

    
    #include <iostream>
    #include <queue>
    #include <algorithm>
    #include <set>
    using namespace std;
    
    int n, m;
    
    vector<int> topsort(vector<int>& inDegree, vector<vector<int>>& adj)
    {
        queue<int> q;
        for(int i = 1; i < inDegree.size(); i++)
            if(!inDegree[i]) q.push(i);
            
        
        vector<int> res;
        while(!q.empty())
        {
            int cur = q.front();
            q.pop();
            res.push_back(cur);
            
            for(int i = 1; i <= n; i++)
            {
                if(adj[cur][i])
                {
                    inDegree[i]--;
                    if(inDegree[i] == 0) q.push(i);
                }
            }
        }
        return res.size() == n ? res : vector<int>();
    }
    
    
    int main()
    {
        cin >> n >> m;
        vector<int> inDegree(n + 1, 0);
        vector<vector<int>> adj(n + 1, vector<int>(n + 1, 0));
        set<pair<int, int>> s;
        for(int i = 1; i <= m; i++)
        {
            int a, b;
            cin >> a >> b;
            adj[a][b] = 1;
            s.insert({a, b});
        }
        for(auto tmp : s)
            inDegree[tmp.second]++;
        vector<int> res = topsort(inDegree, adj);
        
        if(res.empty())
        {
            cout << -1 << endl;
            return 0;
        }
        for(auto & x : res)
            cout << x << " ";
        cout << endl;
        return 0;
    }
    

    邻接表

    class Solution {
    public:
    
        bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
            vector<vector<int> > adj(numCourses);
            vector<int> inDrgree(numCourses, 0);
            for(auto tmp : prerequisites)
            {
                adj[tmp[1]].push_back(tmp[0]);
                inDrgree[tmp[0]]++;
            } 
            return topsort(inDrgree, adj);
        }
    
    
    
    
        bool topsort(vector<int>& inDrgree, vector<vector<int>> &adj)
        {
            queue<int> q;
            for(int i = 0; i < inDrgree.size(); i++)
                if(inDrgree[i] == 0) q.push(i);
            
            int cnt = 0;
            while(!q.empty())
            {
                int cur = q.front();
                q.pop();
                cnt++;
                for(auto &x : adj[cur])
                {
                    inDrgree[x]--;
                    if(inDrgree[x] == 0) q.push(x);
                }
            }
    
            return cnt == inDrgree.size();
        }
    };
    
  • 相关阅读:
    SQL Server 错误(待补充)
    PageLayoutControl的基本操作
    C#:MapControl基本操作代码整理
    ArcGis10.0常见错误
    TocControl控件图层无法显示问题
    ArcGIS 10 安装程序及破解文件
    C# 中运行exe程序
    MySQL触发器更新本表数据异常:Can't update table 'tbl' in stored function/trigger because it
    使用ZBar来读取条形码和二维码的方法
    初识MongoDB
  • 原文地址:https://www.cnblogs.com/Trevo/p/13551456.html
Copyright © 2020-2023  润新知