🔗 🔴 1203. Sort Items by Groups Respecting Dependencies

Problem Statement

題目簡述

有 nn 個物品,編號 0∼n−10 \sim n - 1。第 ii 個物品屬於組別 group[i]\textit{group}[i],若為 −1-1 則不屬於任何組;組別編號為 0∼m−10 \sim m - 1,某個組別可以沒有任何物品。
beforeItems[i]\textit{beforeItems}[i] 列出所有必須排在物品 ii 之前的物品。
請回傳一個物品的排列,使得:

  1. 屬於同一組的物品在排列中必須相鄰;
  2. 滿足所有 beforeItems\textit{beforeItems} 的先後限制。

有多個解時回傳任意一個,無解時回傳空陣列。

Constraints

約束條件

  • 1≤m≤n≤3×1041 \le m \le n \le 3 \times 10^4
  • group.length=beforeItems.length=n\textit{group.length} = \textit{beforeItems.length} = n
  • −1≤group[i]≤m−1-1 \le \textit{group}[i] \le m - 1
  • 0≤beforeItems[i].length≤n−10 \le \textit{beforeItems}[i].\textit{length} \le n - 1
  • 0≤beforeItems[i][j]≤n−10 \le \textit{beforeItems}[i][j] \le n - 1
  • i≠beforeItems[i][j]i \ne \textit{beforeItems}[i][j]
  • beforeItems[i]\textit{beforeItems}[i] 不含重複元素

思路:兩層拓撲排序

「同組相鄰」讓整個排列呈現兩層結構:外層是各個組別排成一列,內層是每個組別內部的物品順序。所以先後限制 y→xy \to x(yy 必須在 xx 前面)也只有兩種情況:

  • yy、xx 同組:只約束該組內部的順序,是一條「物品 → 物品」的邊。
  • yy、xx 不同組:因為組內物品連續排列,要讓 yy 在 xx 前面,就只能讓 yy 所在的整個組排在 xx 所在的組之前,是一條「組 → 組」的邊。
關鍵觀察

外層的組別順序與內層的物品順序彼此獨立:只要組別圖與每個組的物品圖都是 有向無環圖(DAG),分別求出拓撲序再串接,就一定滿足所有限制;任何一張圖有環則整題無解。

常見陷阱

group[i]=−1\textit{group}[i] = -1 的物品沒有組別,彼此之間並不要求相鄰。處理方式是讓每個這樣的物品各自獨立成一個新組(編號從 mm 開始遞增),這樣就能統一用「組」來處理,不必另外分類討論。

建圖

先把每個無組別的物品改配一個新組別編號,此後共有 m′m' 個組別(m≤m′≤m+nm \le m' \le m + n),並記錄 groups[g]\textit{groups}[g] 為組 gg 內的所有物品。

接著分別記錄物品入度 degi\textit{deg}_i 與組別入度 degg\textit{deg}_g,對每個物品 xx 與其 beforeItems[x]\textit{beforeItems}[x] 中的每個 yy,依上面兩種情況連邊:

  • 同組:連 y→xy \to x 到「物品圖」,並讓 degi(x)\textit{deg}_i(x) 加一。
  • 不同組:連 group[y]→group[x]\textit{group}[y] \to \textit{group}[x] 到「組圖」,並讓 degg(group[x])\textit{deg}_g(\textit{group}[x]) 加一。組圖允許重邊,只要入度與邊數一致即可。

物品圖與組圖各自存放,入度也各自存放。物品圖只含組內邊,所以拓撲排序時只會在同一組的物品間流動。

兩次拓撲排序

拓撲排序(Topological Sort) 採用 Kahn 演算法:把入度為 $0$ 的節點放入佇列,每彈出一個節點就把它加入結果,並把後繼節點的入度減一,降到 $0$ 時入隊。若最後結果的長度不等於節點數,代表圖中有環。
  1. 對全部 m′m' 個組做拓撲排序得到組別順序;有環則回傳空陣列。沒有任何物品的空組也會參與排序,但不會貢獻任何物品,在下一步直接跳過即可(也避免對空串列做拓撲排序回傳空陣列而被誤判為有環)。
  2. 依組別順序,逐組對組內物品做拓撲排序,有環則回傳空陣列;否則把該組的物品順序依序接到答案後面。
正確性說明

  • 滿足同組相鄰:每個組的物品在答案中是一段連續區間,因為我們是整組一次接上去的。
  • 滿足先後限制:跨組的限制 y→xy \to x 對應組邊,組別順序保證 group[y]\textit{group}[y] 整段排在 group[x]\textit{group}[x] 前面;同組的限制由該組內的拓撲序保證。
  • 無解判定:同組物品須相鄰,因此跨組限制迫使組與組之間存在嚴格先後順序;若組圖有環,組間先後無法同時滿足;若某組的物品圖有環,組內順序無法同時滿足。兩者都是必要條件,所以回傳空陣列是正確的。

複雜度分析

  • 時間複雜度:O(n+m+E)\mathcal{O}(n + m + E),其中 E=∑i∣beforeItems[i]∣E = \sum_i |\textit{beforeItems}[i]| 為先後限制的總數。建圖掃描所有限制,兩層拓撲排序每個節點與每條邊各處理一次。
  • 空間複雜度:O(n+m+E)\mathcal{O}(n + m + E),用於兩張圖的鄰接表、入度陣列與各組的物品列表。

Code

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
class Solution:
def sortItems(self, n: int, m: int, group: list[int], beforeItems: list[list[int]]) -> list[int]:
groups = [[] for _ in range(m + n)]
for gid, g in enumerate(group):
if g == -1:
g = group[gid] = m
m += 1
groups[g].append(gid)

g_g = [[] for _ in range(m)]
g_i = [[] for _ in range(n)]
deg_g = [0] * m
deg_i = [0] * n
for x, items in enumerate(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

def topologicalSort(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 if len(res) == len(items) else []

order_g = topologicalSort(g_g, deg_g, list(range(m)))
if not order_g:
return []

ans = []
for g in order_g:
if not groups[g]:
continue
order_i = topologicalSort(g_i, deg_i, groups[g])
if not 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.