class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        int importance = 0;
        map<int, Employee*> MAP;
        for (auto em : employees)
        {
            MAP.insert(make_pair(em->id, em));
        }
        map<int, Employee*>::iterator iter;
        iter = MAP.find(id);
        queue<Employee*> Q;
        if (iter != MAP.end())
        {
            int id = iter->first;
            Employee* em = iter->second;
            Q.push(em);

            while (!Q.empty())
            {
                Employee* emp = Q.front();
                Q.pop();
                importance += emp->importance;
                for (auto subid : emp->subordinates)
                {
                    map<int, Employee*>::iterator subiter;
                    subiter = MAP.find(subid);
                    if (subiter != MAP.end())
                    {
                        Q.push(subiter->second);
                    }
                }
            }
        }

        return importance;
    }
};

本题是分支限界法,广度优先搜索,使用map加速查询,防止超时。

posted on 2018-09-30 11:35  Sempron2800+  阅读(111)  评论(0编辑  收藏  举报