中级农民
- 积分
- 116
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-2-8
- 最后登录
- 1970-1-1
|
本帖最后由 zzwzzw435 于 2019-8-21 03:29 编辑
感觉还是可以做,和indegree,outdegree并没有太大关系
- class Solution {
- public int minSemester(int numCourses, int[][] prerequisites,int k) {
- int completedCourses = 0;
- List<Integer>[] nextCourses = new List[numCourses];
- int[] height = new int[numCourses];
- for(int i =0; i<numCourses; i++){
- nextCourses[i] = new ArrayList<>();
- }
- int[] incomingEdgesCount = new int[numCourses];
- for(int[] i:prerequisites){
- incomingEdgesCount[i[0]]++;
- nextCourses[i[1]].add(i[0]);
- }
- // for(int i : incomingEdgesCount){
- // System.out.print(i+" ");
- // }
- for(int i = 0; i < height.length; i++){
- if(height[i] == 0)
- height[i] = getHeight(height,nextCourses,i);
- }
-
- PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
- public int compare(int[] a, int [] b){
- return b[1] - a[1];
- }
- });
- // Add all nodes that have indegree zero to the BFS queue
- for(int i = 0; i<incomingEdgesCount.length; i++){
- if(incomingEdgesCount[i] == 0){
- pq.offer(new int[]{i,height[i]});
- }
- }
- // Bfs starting with indegree 0
- int semester = 0;
- while(!pq.isEmpty()){
- semester++;
- int num = pq.size();
- for(int g = 0; g < k && !pq.isEmpty() && g < num; g++){
- int[] course = pq.poll();
- completedCourses++;
- for(int i : nextCourses[course[0]]){
- incomingEdgesCount[i]--;
- if(incomingEdgesCount[i] == 0){
- pq.offer(new int[]{i,height[i]});
- }
- }
- }
- }
- //System.out.println(completedCourses);
- return semester;
- }
- private int getHeight(int[] height,List<Integer>[] nexts,int idx){
- List<Integer> next = nexts[idx];
- if(next.size() == 0){
- return 1;
- }
- if(height[idx] != 0){
- return height[idx];
- }
- int max = 0;
- for(int n : next){
- max = Math.max(max,getHeight(height,nexts,n));
- }
- return max + 1;
- }
- }
复制代码
|
|