Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Hints: Graph Cutting (Two Vertices, Any Size)

These hints build the tree-DP toolkit used later in E1 (fixed size) and E (three vertices).

Draw the tree from the first example ($1$ in the center, leaves $2,3,4$) with $a=2$, $b=3$. List every connected vertex set that contains both $2$ and $3$. How many are there?
Answer to Hint 1: Exactly two: $\{2,1,3\}$ and $\{2,1,3,4\}$. Any valid set must include the whole path $2 \text{–} 1 \text{–} 3$; the only optional vertex is leaf $4$.
In general, if $S$ is connected and contains both $a$ and $b$, what can you say about the unique path $P(a,b)$ in the tree?
Answer to Hint 3: $P(a,b)$ must be a subset of $S$. So every valid subgraph is “the path $a \leadsto b$” plus possibly extra vertices attached to that path.
Fix a vertex $v$ on $P(a,b)$. Look at a neighbor $x$ of $v$ that is not on the path (a “side branch”). If $S$ uses any vertex from that branch, must it include $x$? Why?
Answer to Hint 5: Yes. The only way into the branch from the rest of $S$ is the edge $(v,x)$. If some deeper vertex were chosen without $x$, the set would be disconnected.
For one side branch rooted at child $x$ (with $x \notin P(a,b)$), define $\mathrm{ways}(x)$ = number of connected subsets of $x$’s subtree that contain $x$ (possibly only $\{x\}$). For a leaf $x$, what is $\mathrm{ways}(x)$? If $x$ has side children $y_1,\ldots,y_k$, how do their choices combine?

Answer to Hint 7: $\mathrm{ways}(x)=1$ for a leaf. In general

$$\mathrm{ways}(x)=\prod_{y \text{ side child of } x}\bigl(1+\mathrm{ways}(y)\bigr),$$

because each side child is either unused ($1$ way) or contributes a connected block that must contain that child ($\mathrm{ways}(y)$ ways). This is the standard “highest-vertex” tree DP for connected induced subgraphs.

At path vertex $v$, each side branch $x$ is either omitted ($1$ way) or fully described by $\mathrm{ways}(x)$. Choices at different side branches are independent. If $v_0,\ldots,v_k$ lists the vertices on $P(a,b)$ from $a$ to $b$, write the final answer as a product over path vertices.

Answer to Hint 9:

$$\text{answer}=\prod_{i=0}^{k}\ \prod_{\substack{x \text{ neighbor of } v_i \\ x \notin P(a,b)}}\bigl(1+\mathrm{ways}(x)\bigr).$$

Algorithm: BFS/DFS from $a$ to find $P(a,b)$, mark path vertices, run the recursive $\mathrm{ways}(\cdot)$ only on side subtrees. Time $O(n)$ per test case.