LeetCode 851. 喧闹和富有(拓扑排序)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 851. 喧闹和富有(拓扑排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
在一組 N 個人(編號為 0, 1, 2, ..., N-1)中,每個人都有不同數目的錢,以及不同程度的安靜(quietness)。
為了方便起見,我們將編號為 x 的人簡稱為 "person x "。
如果能夠肯定 person x 比 person y 更有錢的話,我們會說 richer[i] = [x, y] 。
注意 richer 可能只是有效觀察的一個子集。
另外,如果 person x 的安靜程度為 q ,我們會說 quiet[x] = q 。
現在,返回答案 answer ,其中 answer[x] = y 的前提是,在所有擁有的錢不少于 person x 的人中,person y 是最安靜的人(也就是安靜值 quiet[y] 最小的人)。
示例: 輸入: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] 解釋: answer[0] = 5, person 5 比 person 3 有更多的錢, person 3 比 person 1 有更多的錢, person 1 比 person 0 有更多的錢。 唯一較為安靜(有較低的安靜值 quiet[x])的人是 person 7, 但是目前還不清楚他是否比 person 0 更有錢。answer[7] = 7, 在所有擁有的錢肯定不少于 person 7 的人中 (這可能包括 person 3,4,5,6 以及 7), 最安靜(有較低安靜值 quiet[x])的人是 person 7。其他的答案也可以用類似的推理來解釋。提示: 1 <= quiet.length = N <= 500 0 <= quiet[i] < N,所有 quiet[i] 都不相同。 0 <= richer.length <= N * (N-1) / 2 0 <= richer[i][j] < N richer[i][0] != richer[i][1] richer[i] 都是不同的。 對 richer 的觀察在邏輯上是一致的。來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/loud-and-rich
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
參考:圖Graph–拓撲排序(Topological Sorting)
class Solution { public:vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {int n = quiet.size();vector<vector<int>> g(n);//有向圖,富的指向窮的vector<int> indegree(n, 0);//入度for(auto& r : richer){g[r[0]].push_back(r[1]);indegree[r[1]]++;}queue<int> q;//點的idvector<int> ans(n, -1);for(int i = 0; i< n; i++)ans[i] = i;//初始化最安靜的是自己for(int i = 0; i < n; i++){if(indegree[i] == 0){q.push(i);//最富裕的人,入度為0}}while(!q.empty()){int id = q.front();//人的idint q_val = quiet[ans[id]];//到他這為止,最安靜的人的安靜值q.pop();for(auto nt : g[id])//跟他連接的人(比他窮){if(q_val < quiet[ans[nt]])//比 nt 更安靜的人是 ans[nt], 其安靜值沒有q_val小ans[nt] = ans[id];if(--indegree[nt] == 0)q.push(nt);}}return ans;} };192 ms 33.1 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 851. 喧闹和富有(拓扑排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1535. 找出数组游
- 下一篇: LeetCode 248. 中心对称数