LeetCode-- Employee Importance

来源:互联网 发布:百万公众网络 编辑:程序博客网 时间:2024/06/04 00:22

题目:

You are given a data structure of employee information, which includes the employee's unique id, his importance value and his directsubordinates' id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

Example 1:

Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1Output: 11Explanation: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:

  1. One employee has at most one direct leader and may have several subordinates.
  2. The maximum number of employees won't exceed 2000.

解读:存在一个类为Employee,包含id,importance,subordinate(直系下属id)三个属性。

要求给与一组职员,给定一个职员的id,求出这个职员以及它所有下属包括直系和间接下属的importance之和。


思路:采用BFS方法。 将给定职员的直系下属id入队列,sum的初始值为给定职员本身的importtance值。从队列中取出一个下属id,sum加上它的importance,把该下属标记为已访问,并将该下属所有未访问过的直系下属入队列,循环直到队列为空。


代码:

/*// Employee infoclass Employee {public:    // It's the unique ID of each node.    // unique id of this employee    int id;    // the importance value of this employee    int importance;    // the id of direct subordinates    vector<int> subordinates;};*/class Solution {public:    int getImportance(vector<Employee*> employees, int id) {        int nums = employees.size();        int isvisited[2001];        for(int i = 1;i<= nums;i++) isvisited[i] = 0;        isvisited[id] = 1;        int index = getindex(id, employees);        Employee* m = employees[index];        vector<int> sub = m->subordinates;        int sum = m->importance;        queue<int> q;        for(int i = 0; i < sub.size(); i++) q.push(sub[i]);                while(!q.empty()){            int subid = q.front();            q.pop();            isvisited[subid] = 1;            int index1 = getindex(subid, employees);            sum += employees[index1]->importance;            vector<int> temp = employees[index1]->subordinates;            for(int i = 0; i < temp.size();i++){                if(isvisited[temp[i]] == 0) q.push(temp[i]);            }        }        return sum;    }        int getindex(int id, vector<Employee*> employees){        for(int i = 0 ;i<employees.size(); i++) {            if(employees[i]->id == id) {                return i;            }        }    }};


原创粉丝点击