2023-07-28 Leetcode 2050 并行课程

95 阅读1分钟

Problem: 2050. 并行课程 III

思路

初步想法是DFS+记忆化搜索

解题方法

更合理的方式是发现其无环,利用这种结构,通过拓扑排序来发现最大的加权路径

Code


class Solution {
    public int minimumTime(int n, int[][] relations, int[] time) {
        List<Integer>[] g = new List[n];
        Arrays.setAll(g, k -> new ArrayList<>());
        int[] indeg = new int[n];

        for (int[] e : relations) {
            int a = e[0] - 1;
            int b = e[1] - 1;
            g[a].add(b);
            ++indeg[b];
        }

        Deque<Integer> q = new ArrayDeque<>();
        int[] f = new int[n];
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int v = indeg[i];
            int t = time[i];

            if (v == 0) {
                // 起始点为入度为0的所有节点
                q.offer(i);
                f[i] = t;
                ans = Math.max(ans, t);
            }
        }


        while (!q.isEmpty()) 
        {   
            int i = q.pollFirst();
            for (int j : g[i]) {
                // 遍历其所有后继
                f[j] = Math.max(f[j], f[i] + time[j]);
                ans = Math.max(ans, f[j]);
                if (--indeg[j] == 0) {
                    // 后继的入度为0时, 将其入队
                    q.offer(j);
                }
            }

        }
        return ans;

    }
}