C++ Approach || Topological Sort for DAG || O(n^2 log n)
Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(n^2 log n)\n Add your time complexity here, e.g. O(n) \n\n- Spa
# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2 log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {\n        vector<int> degrees(n);\n        vector<vector<int>> g(n, vector<int>());\n\n        for (auto& edge : edges) {\n            g[edge[0]].push_back(edge[1]);\n            degrees[edge[1]]++;\n        }\n\n        vector<vector<int>> anc(n, vector<int>());\n        queue<int> q;\n        for (int i = 0; i < n; i++) {\n            if (degrees[i] == 0)\n                q.push(i);\n        }\n\n        vector<unordered_set<int>> dup(n);\n        while (!q.empty()) {\n            int fr = q.front();\n            q.pop();\n            for (int c : g[fr]) {\n                dup[c].insert(fr);\n                anc[c].push_back(fr);\n                for (int gr : anc[fr]) {\n                    if (dup[c].find(gr) == dup[c].end()) {\n                        dup[c].insert(gr);\n                        anc[c].push_back(gr);\n                    }\n                }\n                degrees[c]--;\n                if (degrees[c] == 0)\n                    q.push(c);\n            }\n        }\n\n        for (int i = 0; i < n; i++) {\n            sort(anc[i].begin(), anc[i].end());\n        }\n\n        return anc;\n    }\n};\n```
['Graph', 'Topological Sort', 'C++']