1. 程式人生 > 其它 >拓撲排序——喧鬧和富有851

拓撲排序——喧鬧和富有851

喧鬧和富有

題目:喧鬧和富有

有一組 n 個人作為實驗物件,從 0 到 n - 1 編號。
給你一個數組 richer ,其中 richer[i] = [ai, bi] 表示 person ai 比 person bi 更有錢。
另給你一個整數陣列 quiet ,其中 quiet[i] 是 person i 的安靜值。
要求:返回一個整數陣列 answer 作為答案,其中 answer[x] = y 的前提是,y比x富有,同時y是比x富有中最安靜的人。

示例1:

輸入:richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
輸出:[5,5,2,5,4,5,6,7]

題解

建立richer的拓撲排序,根據拓撲排序更新每個人的answer。

class Solution {
        public int[] loudAndRich(int[][] richer, int[] quiet) {
            Queue<Integer> queue = new ArrayDeque<>();
            List<Integer> map[] = new List[quiet.length];
            int book[] = new int[quiet.length];
            int res[] = new int[quiet.length];

            //建立拓撲圖,並計算入度
            for (int i = 0; i < richer.length; i++) {
                if(map[richer[i][0]]==null) map[richer[i][0]]=new ArrayList<>();
                map[richer[i][0]].add(richer[i][1]);
                book[richer[i][1]]++;
            }

            //入度為0,進佇列
            for(int i=0;i<book.length;i++){
                if(book[i]==0) queue.add(i);
                res[i]=i;
            }

            //根據拓撲排序,更新每個人的最安靜的人
            while (!queue.isEmpty())
            {
                int temp=queue.poll();
                if(map[temp]!=null)
                {
                    for(int pool: map[temp])
                    {
                        if(quiet[res[temp]]<quiet[res[pool]]) res[pool]=res[temp];
                        if(--book[pool]==0) queue.add(pool);
                    }
                }
            }
            return res;
        }
    }