• 690. Employee Importance


    问题:

    给定一个公司的上下级关系

    [id, importance, [subordinates]]

    [本员工id,本员工权值,[本员工的下属们的id]]

    求给定员工id,的所有下属员工+自己的权值。

    Example 1:
    Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
    Output: 11
    Explanation:
    Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
    
    Note:
    One employee has at most one direct leader and may have several subordinates.
    The maximum number of employees won't exceed 2000.
    

      

    解法:BFS(广度优先搜索Breadth first search)

    queue: 保存当前处理 id

    visited:保存已经处理过的 id

    遍历queue

    对当前每一个 id:cur,权值相加 res+=cur->importance;

    再将当前 id 的下属们,(没有遍历过的)加入queue中:queue.push(cur->subordinates[x])

    代码参考:

     1 /*
     2 // Definition for Employee.
     3 class Employee {
     4 public:
     5     int id;
     6     int importance;
     7     vector<int> subordinates;
     8 };
     9 */
    10 
    11 class Solution {
    12 public:
    13     int getImportance(vector<Employee*> employees, int id) {
    14         int res = 0;
    15         queue<int> q;
    16         unordered_set<int> visited;
    17         q.push(id);
    18         visited.insert(id);
    19         while(!q.empty()) {
    20             int sz = q.size();
    21             for(int i=0; i<sz; i++) {
    22                 int cur = q.front();
    23                 q.pop();
    24                 for(Employee* e:employees) {
    25                     if(e->id == cur) {
    26                         res += e->importance;
    27                         for(int sub:e->subordinates) {
    28                             if(visited.insert(sub).second==true) {
    29                                 q.push(sub);
    30                             }
    31                         }
    32                         break;
    33                     }
    34                 }
    35             }
    36         }
    37         return res;
    38     }
    39 };
  • 相关阅读:
    C计算double能精确到多少位
    C计算int最大值、最小值
    AndroidStudio右键new无activity
    java替换特殊字符串 $
    lamda表达式排序
    docker toolbox 设置镜像加速
    tomcat优化
    nginx配置相关
    SQL 优化
    elasticsearch 概念初识
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14435930.html
Copyright © 2020-2023  润新知