描述 公司给你提供了所有员工的信息,包括其ID,姓名和所属部门。 以及他们之间的朋友关系,每个关系中由2个ID组成,如 “1, 2” 代表1号员工和2号员工是朋友。 朋友关系不具有传递性,即B、C都是A的朋友,但B和C不一定是朋友。 请计算每个部门中与其它部门的员工有朋友关系的员工个数。
所有的输入中逗号后都跟有一个空格,而且你的程序输出也要和样例格式相同。
返回的列表对顺序没有要求。
员工信息数量 N <= 50 条。
朋友关系的数量 M <= 1000 条。
员工ID都是100以内的数字。
部门数 K <= 20。
示例
输入:
employees = [
"1, Bill, Engineer",
"2, Joe, HR",
"3, Sally, Engineer",
"4, Richard, Business",
"6, Tom, Engineer"
]
friendships = [
"1, 2",
"1, 3",
"3, 4"
]
输出:
"Engineer: 2 of 3"
"HR: 1 of 1"
"Business: 1 of 1"
说明:
样例中,`Engineer`的`1`号员工和`HR`的`2`号员工是朋友关系,
`Engineer` 的`3`号员工和`Business`的`4`号员工是朋友关系,
所以`Engineer`有`2`个人和其它部门有朋友关系,输出"Engineer: 2 of 3“。
此外,HR部门有1人和其他部门有朋友关系,
Business部门有1人和其他部门有朋友关系。
class Solution {
public:
/**
* @param employees: information of the employees
* @param friendships: the friendships of employees
* @return: return the statistics
*/
vector<string> departmentStatistics(vector<string> &employees, vector<string> &friendships) {
// write your code here.
unordered_map<string, int> count;
unordered_map<string, string> id_dep;
for(auto& e : employees)
{
vector<string> t = split(e);
id_dep[t[0]] = t[2];
count[t[2]]++;
}
unordered_map<string, unordered_set<string>> p;
for(auto& f : friendships)
{
vector<string> t = split(f);
if(id_dep[t[0]] != id_dep[t[1]]) // 同一个部门的话,不能计算
{
p[id_dep[t[0]]].insert(t[0]);
p[id_dep[t[1]]].insert(t[1]);
}
}
vector<string> ans;
for(auto& ct : count)
{
int all = ct.second;
string dep = ct.first;
int num = p[dep].size();
ans.push_back(dep + ": " + to_string(num) + " of " + to_string(all));
}
return ans;
}
vector<string> split(string& str)
{
vector<string> t;
string s;
for(auto c : str)
{
if(c ==',')
{
t.push_back(s);
s = "";
}
else if(c != ' ')
s.push_back(c);
}
t.push_back(s);
return t;
}
};