标签:amp schedule des tno finish rap pre while graph
拓扑排序的题目,如果b的前置课程是a,则 a->b。首先计算每个节点的入度,入度为0的结点放到队列中,类似BFS。如果最后有结点的度不为0,说明不行(有环存在)。
class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites); vector<int> indegree=count_indegree(graph); queue<int> q; for (int i=0;i<numCourses;++i){ if (indegree[i]==0) q.push(i); } while (!q.empty()){ int tmp=q.front(); q.pop(); for (int nextnode:graph[tmp]){ --indegree[nextnode]; if (indegree[nextnode]==0) q.push(nextnode); } } for (int i=0;i<numCourses;++i){ if (indegree[i]!=0) return false; } return true; } private: vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites){ vector<unordered_set<int>> graph(numCourses); for (auto pre:prerequisites){ graph[pre.second].insert(pre.first); } return graph; } vector<int> count_indegree(vector<unordered_set<int>> graph){ vector<int> indegree(graph.size(),0); for (auto nextnodes:graph){ for (int nextnode:nextnodes){ ++indegree[nextnode]; } } return indegree; } };
标签:amp schedule des tno finish rap pre while graph
原文地址:https://www.cnblogs.com/hankunyan/p/9527732.html