classSolution: defsortItems(self, n: int, m: int, group: list[int], beforeItems: list[list[int]]) -> list[int]: groups = [[] for _ inrange(m + n)] for gid, g inenumerate(group): if g == -1: g = group[gid] = m m += 1 groups[g].append(gid)
g_g = [[] for _ inrange(m)] g_i = [[] for _ inrange(n)] deg_g = [0] * m deg_i = [0] * n for x, items inenumerate(beforeItems): gx = group[x] for y in items: gy = group[y] if gx == gy: g_i[y].append(x) deg_i[x] += 1 else: g_g[gy].append(gx) deg_g[gx] += 1
deftopologicalSort(g: list[list[int]], deg: list[int], items: list[int]) -> list[int]: q = deque([item for item in items if deg[item] == 0]) res = [] while q: u = q.popleft() res.append(u) for v in g[u]: deg[v] -= 1 if deg[v] == 0: q.append(v) return res iflen(res) == len(items) else []
ans = [] for g in order_g: ifnot groups[g]: continue order_i = topologicalSort(g_i, deg_i, groups[g]) ifnot order_i: return [] ans.extend(order_i) return ans
寫在最後
Cover Image Credit
The cover image was created by @月影暗霜. All rights belong to the original artist.
If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.