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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| class Solution { public: vector<int> sortItems(int n, int m, vector<int>& group, vector<vector<int>>& beforeItems) { vector<vector<int>> groupItem(n + m); int leftId = m; for (int i = 0; i < n; ++i) { if (group[i] == -1) group[i] = leftId++; groupItem[group[i]].emplace_back(i); }
vector<vector<int>> groupGraph(n + m); vector<vector<int>> itemGraph(n); vector<int> groupDegree(n + m, 0); vector<int> itemDegree(n, 0); for (int i = 0; i < n; ++i) { int curGroupId = group[i]; for (auto& item: beforeItems[i]) { int beforeGroupId = group[item]; if (beforeGroupId == curGroupId) { ++itemDegree[i]; itemGraph[item].emplace_back(i); } else { ++groupDegree[curGroupId]; groupGraph[beforeGroupId].emplace_back(curGroupId); } } }
vector<int> id; for (int i = 0; i < n + m; ++i) id.emplace_back(i); vector<int> groupTopSort = topSort(groupDegree, groupGraph, id); if (groupTopSort.size() == 0) return vector<int>{};
vector<int> ans; for (auto& curGroupId: groupTopSort) { int size = groupItem[curGroupId].size(); if (size == 0) continue; vector<int> itemTopSort = topSort(itemDegree, itemGraph, groupItem[curGroupId]); if (itemTopSort.size() == 0) return vector<int>{}; ans.insert(ans.end(), itemTopSort.begin(), itemTopSort.end()); } return ans; } private: vector<int> topSort(vector<int>& indeg, vector<vector<int>>& graph, vector<int>& items) { queue<int> q; for (auto& item: items) if (indeg[item] == 0) q.push(item); vector<int> ans; while (!q.empty()) { int u = q.front(); q.pop(); ans.emplace_back(u); for (auto& v: graph[u]) if (--indeg[v] == 0) q.push(v); } return ans.size() == items.size() ? ans : vector<int>{}; } };
|