标签:strong 数组 返回 odi 红色 维数 还需 set 没有
1 vector<unordered_set<int>> makegraph(int numCourses, vector<pair<int, int>> prerequisites){ 2 vector<unordered_set<int>> graph(numCourses); 3 for(auto pre:prerequisites) graph[pre.second].insert(pre.first); 4 return graph; 5 } 6 vector<int> compute_degrees(vector<unordered_set<int>> graph){ 7 vector<int> degrees(graph.size(),0); 8 for(auto n:graph) 9 for(int neigh:n) 10 degrees[neigh]++; 11 return degrees; 12 } 13 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { 14 vector<unordered_set<int>> graph=makegraph(numCourses,prerequisites); 15 vector<int> degrees=compute_degrees(graph); 16 for(int i=0;i<numCourses;i++){ 17 int j=0; 18 for(j;j<numCourses;j++) 19 if(!degrees[j]) break; 20 if(j==numCourses) return false; 21 degrees[j]=-1; 22 for(int neigh:graph[j]) 23 degrees[neigh]--; 24 } 25 return true; 26 } 27 };
1 //dfs 2 vector<unordered_set<int>> makegraph(int numCourses, vector<pair<int, int>>& prerequisites){ 3 vector<unordered_set<int>> graph(numCourses); 4 for(auto pre:prerequisites) 5 graph[pre.second].insert(pre.first); 6 return graph; 7 } 8 bool dfscycle(vector<unordered_set<int>>& graph,int i,vector<bool>& onpath,vector<bool>& visit){ 9 if(visit[i]) return false; 10 visit[i]=onpath[i]=true; 11 for(int neigh:graph[i]) 12 if(onpath[neigh]||dfscycle(graph,neigh,onpath,visit)) 13 return true; 14 return onpath[i]=false; 15 } 16 bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { 17 vector<unordered_set<int>> graph=makegraph(numCourses,prerequisites); 18 vector<bool> visit(numCourses,false),onpath(numCourses,false); 19 for(int i=0;i<numCourses;i++) 20 if(!visit[i]&&dfscycle(graph,i,onpath,visit)) 21 return false; 22 return true; 23 }
标签:strong 数组 返回 odi 红色 维数 还需 set 没有
原文地址:http://www.cnblogs.com/weedboy/p/6814201.html