zoukankan      html  css  js  c++  java
  • Topological Sort

    DFS:

    class Solution {
    public:
        vector<int> res;
        bool detectedCycle = false;
        vector<int> findOrder(int n, vector<pair<int, int>>& pres) {
            if (n < 1)  return res;
            
            vector<unordered_set<int>> v(n);
            for (const auto& p : pres)
                v[p.second].insert(p.first);
            
            vector<int> visited(n, -1);
            for (int i = 0; i < n; i++)
                dfs(v, visited, i);
            
            reverse(res.begin(), res.end());            // result in reverse order
            return detectedCycle ? vector<int>() : res;
        }
        void dfs(vector<unordered_set<int>>& v, vector<int>& visited, int n) {
            if (detectedCycle || visited[n] != -1)  return;
            visited[n] = 1;
            for (int i : v[n]) {
                if (visited[i] == 1)
                    detectedCycle = true;
                else if (visited[i] == 2)
                    continue;
                else
                    dfs(v, visited, i);
            }
            visited[n] = 2;
            res.push_back(n);       // push current node to the end, and final result is in reverse order.
        }
    };

    Topological sort:

    class Solution {
    public:
        vector<int> findOrder(int n, vector<pair<int, int>>& pres) {
            vector<int> res;    if (n < 1)  return res;
            
            vector<unordered_set<int>> v(n);
            vector<int> d(n, 0);                // in-degree of each node
            for (const auto& p : pres) {
                v[p.second].insert(p.first);
                d[p.first]++;
            }
            
            for (int k = 0; k < n; k++) {
                int cur = 0;   // find a v which indegree is 0, then we can delete it
                while (cur < n && d[cur] != 0) cur++;
                if (cur == n)   { return vector<int>(); }
                for (auto nb : v[cur])
                    d[nb]--;
                res.push_back(cur);
                d[cur] = -1;
            }
            return res;
        }
    };
  • 相关阅读:
    [CAMCOCO][C#]我的系统架构.服务器端.(一)
    开博啦,加油!!
    Django RestFul framework Serializer序列化器的使用(定义)
    Django项目快速搭建
    Django简介
    python搭建虚拟环境
    大专生自学web前端前前后后
    实现资源国际化
    利用ajax实现页面动态修改
    七牛使用
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9001333.html
Copyright © 2011-2022 走看看