本文主要是介绍LeetCode 690.Employee Importance,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
LeetCode 690.Employee Importance
Description:
You are given a data structure of employee information, which includes the employee’s unique id, his importance value and his direct subordinates’ 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:
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.
分析:
这道题做的我好气,倒不是说题难,相反题简单,然而我在写main函数一直写不好Employee类,使我很烦躁,最后写好了想把代码输入写的漂亮一点,方便读者阅读,所以我采用了中文提示输入,然而sublime怎么鬼畜了,中文乱码,网上说可以用convert to UTF8或者GBK support解决,然而我早就已经安装了这两个packet了,后来我放弃了,改成英文提示输入。。。
回到这道题来,也不是很容易,因为涉及到不太熟悉的
unordered_map
库函数。
首先遍历所有员工把每一个id和员工对应起来放进unordered_map
中,然后把该id对应的员工的importance加上,最后递归得到该id对应员工的直接下属的importance并把它们加上,即可。
代码如下:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Employee info
class Employee {
public:// It's the unique ID of each node.// unique id of this employeeint id;// the importance value of this employeeint importance;// the id of direct subordinatesvector<int> subordinates;
};
class Solution {
public:int getImportance(vector<Employee*> employees, int id) {unordered_map<int, Employee*> um;for (auto e : employees) {um[e->id] = e;}return getSum(um, id);}
private:int getSum(unordered_map<int, Employee*>& um, int id) {int ans = um[id]->importance;for (auto e : um[id]->subordinates) {ans += getSum(um, e);}return ans;}
};
int main() {int n, num;cout << "Please input the number of Employees:";cin >> n;vector<Employee*> ems;Employee em[n];for (int i = 0; i < n; i++) {cin >> em[i].id >> em[i].importance;cout << "Please input the number of direct Employees:";cin >> num;int temp;for (int j = 0; j < num; j++) { cin >> temp;em[i].subordinates.push_back(temp);}ems.push_back(&em[i]);}// cout << ems.size() << endl;// for (int i = 0; i < ems.size(); i++) {// cout << ems[i]->id << " " << ems[i]->importance << endl;// }int idNum;cin >> idNum;Solution s;cout << s.getImportance(ems, idNum) << endl;return 0;
}
/*
input:
Please input the number of Employees:3
1
5
Please input the number of direct Employees:2
2 32
3
Please input the number of direct Employees:03
3
Please input the number of Employees:01output:
11*/
这篇关于LeetCode 690.Employee Importance的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!