leetcode 每日一题 851喧闹和富有
作者:互联网
思路,将题中给的数据转化为一棵树,越穷的在上面,一定比其富有的则是在其下方,找答案就是向下遍历一遍就是了。
class Solution {
public:
struct human{
int q;
int mostQuiet = -1;
int mostQuietIndex = -1;
vector <int> richer1;
};
vector <human> nums;
int l1,l2;
int nowIndex = -1;
vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
l1 = quiet.size();
for(int i = 0; i < l1; i++){
human t;
t.q = quiet[i];
nums.push_back(t);
}
l2 = richer.size();
for(int i = 0; i < l2; i++){
nums[richer[i][1]].richer1.push_back(richer[i][0]);
}
vector <int> an;
for(int i = 0; i < l1; i++){
dfs(i);
an.push_back(nums[i].mostQuietIndex);
}
return an;
}
void dfs(int index){
if(nums[index].mostQuiet != -1){
return;
}
nums[index].mostQuiet = nums[index].q;
nums[index].mostQuietIndex = index;
vector <int> sons = nums[index].richer1;
int l = sons.size();
for(int i = 0; i < l; i++){
dfs(sons[i]);
if(nums[sons[i]].mostQuiet < nums[index].mostQuiet){
nums[index].mostQuiet = nums[sons[i]].mostQuiet;
nums[index].mostQuietIndex = nums[sons[i]].mostQuietIndex;
}
}
}
};
标签:index,sons,851,nums,int,喧闹,vector,mostQuiet,leetcode 来源: https://blog.csdn.net/weixin_44104745/article/details/121953493