[Topological sort] leetcode 1136 Parallel Courses

 problem:https://leetcode.com/contest/biweekly-contest-5/problems/parallel-courses/

         This question is a hard question leetcode bi-weekly game, in fact, the difficulty is not so high. Entitled Advanced Placement courses given relationship, for example, to study courses B, it must take some courses A, output On completion of the minimum number of semester for all courses.

         The basic idea of ​​topological sorting:

         (1) (number of points of the vertex side) for directed graphs, the records of all of the vertices

         (2) Find all the vertices of degree 0 of the vertices in a queue

         (3) an element from the queue pop, the vertex is currently satisfying the condition of vertices may count by one, and it points to the degree of vertex is decremented by one, repeat (2) (3) until the queue is empty

         If you have not found the degree of vertex 0, and the current count of all vertices not yet covered, then that may occur in the loop to FIG.

class Solution {
public:
    vector<unordered_set<int>> g;
    int minimumSemesters(int N, vector<vector<int>>& r) {
        vector<int> indegree(N + 1, 0);
        g.resize(N + 1);
        for(int i = 0;i < r.size();i++)
        {
            g[r[i][0]].insert(r[i][1]);
            indegree[r[i][1]]++;
        }
        queue<int> q;
        for(int i = 1;i <= N;i++)
        {
            if(indegree[i] == 0)
            {
                q.push(i);
            }
        }

        int res = 0;
        int count = 0;
        while(!q.empty())
        {
            int size = q.size();
            for(int i = 0;i < size;i++)
            {
                int cur = q.front();
                q.pop();
                count++;
                        
                for(auto& next : g[cur])
                {
                    indegree[next]--;
                    if(indegree[next] == 0)
                    {
                        q.push(next);
                    }
                }   
            }
            res++;
        }
        if(count != N) return -1;

        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11260936.html