classSolution: defmaximumInvitations(self, favorite: List[int]) -> int: n = len(favorite) ind = [0] * n for f in favorite: ind[f] += 1 rg = [[] for _ inrange(n)] q = deque(i for i, d inenumerate(ind) if d == 0) while q: # 拓樸排序 u = q.popleft() v = favorite[u] rg[v].append(u) # 反向建圖 ind[v] -= 1 if ind[v] == 0: q.append(v)
# 通過 reverse graph,找到最大樹高 defrdfs(u: int) -> int: res = 1 for v in rg[u]: res = max(res, rdfs(v) + 1) return res max_ring = sum_chain = 0 for u, d inenumerate(ind): # 遍歷所有基環上的點 if d == 0: # 入度為 0 代表非基環上的點或者已經訪問過,跳過 continue
# 找到基環上的所有點 rings = [u] v = favorite[u] while v != u: rings.append(v) v = favorite[v] for v in rings: ind[v] = 0# 將基環上的點的入度標記為 0,避免重複訪問 # 若基環長度為 2,則可以選擇基環以及兩側的最長鏈,且其仍然可以展開為鏈,因此可以有多個長度為 2 的基環 iflen(rings) == 2: sum_chain += rdfs(u) + rdfs(favorite[u]) # 若基環長度大於 2,則只能選擇基環本身 else: max_ring = max(max_ring, len(rings))
In a beautiful anime style, a young girl stands in front of a backdrop of densely blooming cherry blossoms. She is wearing a white short-sleeved shirt paired with a light purple skirt and a purple ribbon, exuding a fresh and elegant aura. Her hair is a deep brown short cut, with bangs parted to reveal a delicate face. Her left hand is raised gently while her right hand holds a bouquet of pink flowers, posing naturally. The background is slightly blurred but filled with an abundance of cherry blossoms, enhancing the romantic and serene atmosphere. The contrast is intensified, making the colors more vibrant and the overall scene more striking, capturing a poetic and picturesque moment.