zoukankan      html  css  js  c++  java
  • Course Schedule

    There are a total of n courses you have to take, labeled from 0 to n - 1.

    Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

    Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

    For example:

    2, [[1,0]]

    There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

    2, [[1,0],[0,1]]

    There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

    Note:
    The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

    Analyse: Using BFS. 

     1 class Solution {
     2 public:
     3     bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
     4         if(prerequisites.empty()) return true;
     5         
     6         int n = prerequisites.size();
     7         vector<vector<bool> > graph(numCourses, vector<bool>(numCourses, false));
     8         vector<int> indegree(numCourses, 0);
     9         for(int i = 0; i < n; i++){
    10             if(graph[prerequisites[i].second][prerequisites[i].first] == false){//avoid duplicate pairs
    11                 graph[prerequisites[i].second][prerequisites[i].first] = true;
    12                 indegree[prerequisites[i].first]++;
    13             }
    14         }
    15         stack<int> stk;
    16         int count = 0;
    17         for(int i = 0; i < numCourses; i++){
    18             if(indegree[i] == 0)
    19                 stk.push(i);
    20         }
    21         while(!stk.empty()){
    22             int source = stk.top();
    23             stk.pop();
    24             count++;
    25             for(int i = 0; i < numCourses; i++){
    26                 if(graph[source][i]){
    27                     indegree[i]--;
    28                     if(indegree[i] == 0)
    29                         stk.push(i);
    30                 }
    31             }
    32         }
    33         return count == numCourses;
    34     }
    35     //1. construct a graph and compute each node's indegree
    36     //2. push all nodes with 0 indegree to a stack
    37     //3. pop out the first node, decrease its neighbour's degree by 1
    38     //   push all nodes with 0 indegree to a stack and continue
    39 };
  • 相关阅读:
    SPOJ VJudge QTREE
    LCA 在线倍增法 求最近公共祖先
    Codevs 2370 小机房的树
    51Nod-1632-B君的连通
    51Nod--1100-斜率最大
    51Nod-1276-岛屿的数量
    51Nod-1270-数组的最大代价
    poj
    hihocoder Week136 -- 优化延迟
    poj-1035-Spell Checker
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5197015.html
Copyright © 2011-2022 走看看