338. Familystrokes -

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).

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; 338. FamilyStrokes

print(internal + horizontal)

Proof. By definition a leaf has no children, thus rule 1 (vertical stroke) and rule 2 (horizontal stroke) are both inapplicable. ∎ Every internal node (node with childCnt ≥ 1 ) requires exactly one vertical stroke . By definition a leaf has no children, thus

cout << internalCnt + horizontalCnt << '\n'; return 0; internalCnt + horizontalCnt &lt

int main() long long horizontalCnt = 0; // # v

Memory – The adjacency list stores 2·(N‑1) integers, plus a stack/queue of at most N entries and a few counters: O(N) .