338. Familystrokes ❲1080p – 4K❳
while (!st.empty()) int v = st.back(); st.pop_back(); int childCnt = 0; for (int to : g[v]) if (to == parent[v]) continue; parent[to] = v; ++childCnt; st.push_back(to); if (childCnt > 0) ++internalCnt; if (childCnt >= 2) ++horizontalCnt;
if childCnt > 0: // v has at least one child → internal internalCnt += 1 if childCnt >= 2: horizontalCnt += 1
Memory – The adjacency list stores 2·(N‑1) integers, plus a stack/queue of at most N entries and a few counters: O(N) . 338. FamilyStrokes
while stack not empty: v, p = pop(stack) childCnt = 0 for each w in G[v]: if w == p: continue // ignore the edge back to parent childCnt += 1 push (w, v) on stack
int main() long long horizontalCnt = 0; // # childCnt >= 2 while (
print(internal + horizontal)
Proof. If childCnt ≥ 2 : the children occupy at least two columns on the next row, so a horizontal line is needed to connect the leftmost to the rightmost child (rule 2). Only‑if childCnt = 1 : the sole child
Only‑if childCnt = 1 : the sole child is placed directly under the parent; the horizontal segment would have length zero and is omitted by the drawing convention. ∎ The number of strokes contributed by a node v is