-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2115.cpp
More file actions
47 lines (42 loc) · 1.36 KB
/
Copy path2115.cpp
File metadata and controls
47 lines (42 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
const int SIZE = 101;
public:
vector<string> findAllRecipes(vector<string> &recipes, vector<vector<string>> &ingredients,
vector<string> &supplies) {
unordered_map<string, int> hash;
unordered_set<string> us(supplies.begin(), supplies.end());
vector<vector<int>> adj(SIZE);
vector<int> count(SIZE);
vector<string> finished;
for (int i = 0; i < recipes.size(); i++)
hash.insert({recipes[i], i});
for (int i = 0; i < recipes.size(); i++) {
for (string &s : ingredients[i])
if (!us.count(s)) {
count[i]++;
if (!hash.count(s))
count[i] = INT_MAX;
else
adj[hash[s]].push_back(i);
}
}
queue<int> q;
for (int i = 0; i < recipes.size(); i++) {
if (!count[i]) {
q.push(i);
finished.push_back(recipes[i]);
}
}
while (!q.empty()) {
int root = q.front();
q.pop();
for (int c : adj[root]) {
if (!--count[c]) {
q.push(c);
finished.push_back(recipes[c]);
}
}
}
return finished;
}
};