Paste: a

Author: aa
Mode: c++
Date: Thu, 12 May 2022 05:37:07
Plain Text |
class Solution {
private:
    unordered_map<string, int> suppHash; 
    unordered_map<string, vector<string> > ing_2_rec; 
public:
    vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
        unordered_map<string, int> count;

        //建图
        for(int i=0;i<ingredients.size();i++)
        {
            auto ingredient=ingredients[i];
            count[recipes[i]]=ingredient.size();
            for(auto ingr:ingredient)
            {
                ing_2_rec[ingr].push_back(recipes[i]);
            }
        }

        queue<string> q;
        vector<string> ans;
        for(auto sup:supplies)
        {q.push(sup);
        }
        //BFS
        while(!q.empty())
        {
            string cur=q.front();
            q.pop();
            for(auto son:ing_2_rec[cur])
            {
                count[son]--;
                if(count[son]==0)
                {
                    q.push(son);
                    ans.push_back(son);
                }
            }
        }

        return ans;
    }

};

New Annotation

Summary:
Author:
Mode:
Body: