|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<int> sortItems(int n, int m, vector<int>& group, vector<vector<int>>& beforeItems) |
| 4 | + { |
| 5 | + unordered_map<int, unordered_set<int>>groupItems; |
| 6 | + int nextGroupId = m; |
| 7 | + |
| 8 | + for (int i=0; i<n; i++) |
| 9 | + { |
| 10 | + if (group[i]==-1) |
| 11 | + { |
| 12 | + group[i] = nextGroupId; |
| 13 | + nextGroupId += 1; |
| 14 | + } |
| 15 | + groupItems[group[i]].insert(i); |
| 16 | + } |
| 17 | + |
| 18 | + // build graph inside each group |
| 19 | + unordered_map<int, unordered_set<int>>next; |
| 20 | + unordered_map<int, int>inDegree; |
| 21 | + for (int i=0; i<n; i++) |
| 22 | + for (int j: beforeItems[i]) |
| 23 | + { |
| 24 | + if (group[i]!=group[j]) continue; |
| 25 | + if (next[j].find(i)==next[j].end()) |
| 26 | + { |
| 27 | + next[j].insert(i); |
| 28 | + inDegree[i] += 1; |
| 29 | + } |
| 30 | + } |
| 31 | + // sort nodes inside each group |
| 32 | + unordered_map<int, vector<int>>groupItemsOrdered; |
| 33 | + for (auto x: groupItems) |
| 34 | + { |
| 35 | + int groupId = x.first; |
| 36 | + groupItemsOrdered[groupId] = topologySort(groupItems[groupId], next, inDegree); |
| 37 | + if (groupItemsOrdered[groupId].size() != groupItems[groupId].size()) |
| 38 | + return {}; |
| 39 | + } |
| 40 | + |
| 41 | + // build graph among groups |
| 42 | + next.clear(); |
| 43 | + inDegree.clear(); |
| 44 | + for (int i=0; i<n; i++) |
| 45 | + for (int j: beforeItems[i]) |
| 46 | + { |
| 47 | + if (group[i]==group[j]) continue; |
| 48 | + if (next[group[j]].find(group[i])==next[group[j]].end()) |
| 49 | + { |
| 50 | + next[group[j]].insert(group[i]); |
| 51 | + inDegree[group[i]] += 1; |
| 52 | + } |
| 53 | + } |
| 54 | + // sort groups |
| 55 | + unordered_set<int>groups; |
| 56 | + for (int i=0; i<n; i++) groups.insert(group[i]); |
| 57 | + vector<int>groupOrdered = topologySort(groups, next, inDegree); |
| 58 | + |
| 59 | + vector<int>rets; |
| 60 | + for (int groupId: groupOrdered) |
| 61 | + { |
| 62 | + for (auto node: groupItemsOrdered[groupId]) |
| 63 | + rets.push_back(node); |
| 64 | + } |
| 65 | + return rets; |
| 66 | + } |
| 67 | + |
| 68 | + vector<int> topologySort (unordered_set<int>&nodes, unordered_map<int, unordered_set<int>>&next, unordered_map<int, int>&inDegree) |
| 69 | + { |
| 70 | + queue<int>q; |
| 71 | + vector<int>ret; |
| 72 | + for (auto node: nodes) |
| 73 | + { |
| 74 | + if (inDegree[node]==0) |
| 75 | + q.push(node); |
| 76 | + } |
| 77 | + while (!q.empty()) |
| 78 | + { |
| 79 | + int cur = q.front(); |
| 80 | + q.pop(); |
| 81 | + ret.push_back(cur); |
| 82 | + for (auto next: next[cur] ) |
| 83 | + { |
| 84 | + inDegree[next] -= 1; |
| 85 | + if (inDegree[next] == 0) |
| 86 | + q.push(next); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if (ret.size()==nodes.size()) |
| 91 | + return ret; |
| 92 | + else |
| 93 | + return {}; |
| 94 | + } |
| 95 | +}; |
0 commit comments