FOCUS-ASTU-TECH-COMMUNITY-ADVANCED-CP-CONTEST-1
Difference between en1 and en2, changed 2 character(s)
#[contest:734480]↵
↵
Hello everyone!↵
↵
Welcome to the editorial for **FOCUS-ASTU-TECH-COMMUNITY-ADVANCED-CP-CONTEST-1**. Our topics this season were **Recursion, Trees and Linked Lists**, so this set mixes classic implementation and constructive problems with problems where those three ideas give the cleanest solution (tree depth, tree construction, tree DP, recursive search and backtracking, and walking along chains of pointers).↵
↵
Below you will find hints, tutorials, and solutions for each problem. We used spoiler tags to keep things clean. Try to solve it yourself before clicking!↵
↵
Happy coding!↵
↵
## Problem-A:[problem:734480A]↵
**Tags:** `Linked List` `Math` `Parity` `Constructive`<br>↵
**Difficulty:** ⭐⭐ (Easy)↵
↵
This problem looks like a game on a string, but hidden inside it are several **linked lists**.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
You are given a binary string `s` of length `n` and an integer `k`.  ↵
↵
In one move you choose an index `i` with  ↵
$$1 \le i \le n-k$$  ↵
and **flip both** `s[i]` and `s[i+k]` (`0 -> 1`, `1 -> 0`).  ↵
↵
You can do as many moves as you like. Can you make the **whole string equal to zero**?↵
↵
---↵
↵
#### Example↵
`s = 10110`, `k = 2`. Choosing `i = 2` flips positions 2 and 4: `10110 -> 11100`.↵
↵
---↵
↵
#### Input Constraints↵
$$1 \le k \le n \le 2 \cdot 10^5$$  ↵
and there are up to `10^4` test cases (sum of `n` is bounded).↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- A move only touches positions `i` and `i + k`. So positions with **different remainders modulo `k`** never interact.  ↵
- Group the positions by `i mod k`. Each group looks like `i, i+k, i+2k, ...`  ↵
- A move flips **two** characters of the **same** group. What can never change when you flip two things at once?↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Step 1: Split the string into chains↵
Every index `i` has exactly one "next" index: `i + k`. Following this pointer gives a **chain** (a singly linked list!):  ↵
↵
`i -> i+k -> i+2k -> ...`  ↵
↵
There are exactly `k` chains (one for each starting index `0 .. k-1`), and they never touch each other.  ↵
↵
A move chooses **two neighbouring nodes of one chain** and flips both.↵
↵
---↵
↵
### Step 2: The invariant↵
Flipping two characters changes the number of `1`s in that chain by `-2`, `0` or `+2`. So the **parity** (odd/even) of the number of ones in every chain never changes.  ↵
↵
At the end we want all zeros, which means **every chain has 0 ones (even)**. Therefore:  ↵
↵
> If some chain has an **odd** number of ones, the answer is `NO`.↵
↵
---↵
↵
### Step 3: Even is always enough↵
Suppose a chain has an even number of ones. Pair them up from left to right. To clear a pair at chain positions `p < q`, flip the neighbouring pairs `(p,p+1), (p+1,p+2), ..., (q-1,q)`. Every node strictly between `p` and `q` is flipped twice (back to normal), while `p` and `q` are flipped once, so both ones disappear.  ↵
↵
So the answer is `YES` exactly when **every chain has an even number of ones**.↵
↵
---↵
↵
### Algorithm↵
1. For `start = 0 .. k-1` walk the chain `start, start+k, start+2k, ...` (exactly like traversing a linked list: `node = node.next`).  ↵
2. Count the ones in this chain. If the count is odd, print `NO`.  ↵
3. If all chains are even, print `YES`.↵
↵
---↵
↵
### Common Pitfalls↵
- **`k = n`:** no move is possible. Every chain has one node, so it is `YES` only if the string is already all zeros. The rule above handles this automatically.  ↵
- Simulating the moves directly (BFS over strings) is far too slow. The invariant is the whole point.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
↵
def solve():↵
    data = sys.stdin.read().split()↵
    t = int(data[0]); pos = 1↵
    out = []↵
    for _ in range(t):↵
        n, k = int(data[pos]), int(data[pos + 1]); s = data[pos + 2]; pos += 3↵
        ok = True↵
        # every residue class (i, i+k, i+2k, ...) is one "linked list"↵
        for start in range(k):↵
            ones = 0↵
            i = start↵
            while i < n:              # walk: node -> node.next (i + k)↵
                if s[i] == '1':↵
                    ones += 1↵
                i += k↵
            if ones % 2 == 1:↵
                ok = False↵
                break↵
        out.append("YES" if ok else "NO")↵
    print("\n".join(out))↵
↵
solve()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(n). Every index belongs to exactly one chain and is visited once.  ↵
- **Space:** O(1) extra (we only keep a counter), apart from reading the input.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: One XOR per remainder">↵
Instead of walking each chain separately, keep an array `parity[0..k-1]` and scan the string once:↵
↵
~~~~~↵
parity = [0] * k↵
for i in range(n):↵
    if s[i] == '1':↵
        parity[i % k] ^= 1↵
print("YES" if not any(parity) else "NO")↵
~~~~~↵
↵
It is the same idea (one parity per chain), just done in a single left-to-right pass. The linked-list version is easier to *see*, the array version is shorter to write.↵
</spoiler>↵
↵
## Problem-B:[problem:734480B]↵
**Tags:** `Strings` `Greedy` `Implementation` `Recursion`<br>↵
**Difficulty:** ⭐ (Very Easy)↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
You are given a binary string `s` (made of `0` and `1`). In one move you may **erase one `0`** from anywhere in the string.  ↵
↵
You want all the `1`s to form **one continuous block** (no `0` between two `1`s).  ↵
↵
Find the **minimum number of zeros** you must erase.↵
↵
---↵
↵
#### Example↵
`s = 010011`  ↵
The ones are at positions 2, 5, 6. Between the first and the last `1` there are two zeros (`0 0` in `1 0 0 1`), so we erase both and get `011` -> answer `2`.↵
↵
---↵
↵
#### Input Constraints↵
$$1 \le |s| \le 100$$  ↵
and up to 100 test cases.↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- Zeros **before the first `1`** and **after the last `1`** never hurt. Do you ever need to erase them?  ↵
- What about a zero **between** two `1`s?  ↵
- What if the string has **no `1` at all**?↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Observation↵
- A zero at the very beginning or at the very end can stay: it is not between any two ones.  ↵
- Every zero that is **strictly between the first `1` and the last `1`** separates two ones, so it must be erased. Erasing exactly those zeros is also enough.↵
↵
So the answer is simply:↵
↵
> the number of `0`s in the segment from the **first `1`** to the **last `1`**.↵
↵
If there is no `1`, there is nothing to connect, so the answer is `0`.↵
↵
---↵
↵
### Steps↵
1. Find `first = s.find('1')`. If it is `-1`, print `0`.  ↵
2. Find `last = s.rfind('1')`.  ↵
3. Print `s[first:last+1].count('0')`.↵
↵
---↵
↵
### Example Walkthrough↵
`s = 1111000` -> first `1` at index 0, last `1` at index 3 -> segment `1111` has `0` zeros -> answer `0`.  ↵
`s = 10101` -> segment is the whole string, which has two zeros -> answer `2`.↵
↵
---↵
↵
### Common Pitfalls↵
- Forgetting the all-zeros string (`s.find` returns `-1`).  ↵
- Counting **all** zeros in the string instead of only those between the first and last `1`.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
t = int(input())↵
for _ in range(t):↵
    s = input().strip()↵
    first = s.find('1')↵
    last = s.rfind('1')↵
    if first == -1:↵
        print(0)↵
    else:↵
        print(s[first:last + 1].count('0'))↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(|s|) per test case.  ↵
- **Space:** O(|s|) for the slice (O(1) if you count with a loop instead).↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Recursion (peel the ends)">↵
**Topic:** Recursion  ↵
↵
Think of the string as a problem that gets smaller each time we remove a useless character:↵
↵
- **Base case:** the string is empty -> `0`.  ↵
- If it starts with `0` -> that zero is useless, solve for `s[1:]`.  ↵
- If it ends with `0` -> solve for `s[:-1]`.  ↵
- Otherwise the string starts and ends with `1`: every zero inside must be erased -> `s.count('0')`.↵
↵
~~~~~↵
def solve(s):↵
    if not s:↵
        return 0↵
    if s[0] == '0':              # leading zero never needs erasing↵
        return solve(s[1:])↵
    if s[-1] == '0':             # trailing zero never needs erasing↵
        return solve(s[:-1])↵
    return s.count('0')          # both ends are '1': every zero inside must go↵
↵
t = int(input())↵
for _ in range(t):↵
    print(solve(input().strip()))↵
~~~~~↵
↵
The recursion depth is at most `|s| <= 100`, so there is no stack problem. It is not faster than the main solution, but it is a nice example of *"shrink the input and trust the recursion"*.↵
</spoiler>↵
↵
## Problem-C:[problem:734480C]↵
**Tags:** `Trees` `Recursion` `DFS` `Linked List`<br>↵
**Difficulty:** ⭐⭐ (Easy)↵
↵
A very good first problem on **tree depth**.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Story↵
A company has `n` employees. Every employee `i` has either **no manager** (`p_i = -1`) or exactly one direct manager `p_i`.  ↵
↵
An employee `a` is a **superior** of `b` if `a` is `b`'s manager, or the manager of `b`'s manager, and so on.  ↵
↵
The employees must be split into **groups** for a party so that **nobody in a group is a superior of anybody else in the same group**.  ↵
↵
Find the **minimum number of groups**.↵
↵
---↵
↵
#### Input↵
- `n` (`1 <= n <= 2000`)  ↵
- `n` numbers `p_1, ..., p_n`, where `p_i = -1` or `1 <= p_i <= n`  ↵
↵
It is guaranteed that there are no cycles.↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- Draw the employees as a **forest** (many trees): an arrow from every employee to the manager.  ↵
- Take the longest chain `employee -> manager -> manager's manager -> ... -> boss`. All people on it are superiors of each other, so they need different groups.  ↵
- Is that lower bound enough? What if you put everybody with the **same depth** in one group?↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Idea: the answer is the maximum depth↵
Define the **depth** of an employee as the number of people on the path up to the boss (the boss has depth `1`).↵
↵
**Lower bound.** The longest chain has `D` people and all of them are superiors of each other, so at least `D` groups are needed.↵
↵
**Upper bound.** Put all employees of the same depth into the same group. Two people with the same depth can never be superior/subordinate (a superior is always strictly higher up), so this grouping is valid and uses exactly `D` groups.↵
↵
So the answer is the **maximum depth** over all nodes of the forest.↵
↵
---↵
↵
### Computing the depth recursively↵
This is the same idea as the *maximum depth of a binary tree* from our Trees lecture, but upside down:↵
↵
- **Base case:** if `p_v = -1`, then `depth(v) = 1`.  ↵
- **Recursive case:** `depth(v) = 1 + depth(p_v)`.↵
↵
Since many employees share the same ancestors we store the answer in a `memo` array, so each employee is computed only once.↵
↵
---↵
↵
### Common Pitfalls↵
- Employees are **not** given in order (a manager can have a bigger index than the employee), so you cannot just compute `depth[i] = depth[p_i] + 1` in a left-to-right loop. The recursion handles any order.  ↵
- The chain can be `2000` long, so raise the recursion limit in Python (`sys.setrecursionlimit`).  ↵
- Remember there can be **several roots** (a forest, not a single tree).↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
sys.setrecursionlimit(10000)↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    n = int(data[0])↵
    parent = [0] + [int(x) for x in data[1:n + 1]]   # 1-indexed, -1 = no manager↵
    memo = [0] * (n + 1)↵
↵
    def depth(v):↵
        if parent[v] == -1:          # base case: the boss of a tree↵
            return 1↵
        if memo[v]:                  # already solved↵
            return memo[v]↵
        memo[v] = 1 + depth(parent[v])   # recursive case↵
        return memo[v]↵
↵
    print(max(depth(v) for v in range(1, n + 1)))↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(n). Every employee is solved once thanks to the memo.  ↵
- **Space:** O(n) for the arrays and the recursion stack.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Walk up the manager pointers (Linked List)">↵
**Topic:** Linked List  ↵
↵
Each employee stores a pointer to the manager, just like `node.next` in a singly linked list that ends at `-1`. So the depth of `v` is simply the **length of the list** starting at `v`:↵
↵
~~~~~↵
n = int(input())↵
manager = [0] + [int(input()) for _ in range(n)]↵
best = 0↵
for v in range(1, n + 1):↵
    length = 0↵
    cur = v↵
    while cur != -1:      # traverse like a linked list↵
        length += 1↵
        cur = manager[cur]↵
    best = max(best, length)↵
print(best)↵
~~~~~↵
↵
This is `O(n^2)` in the worst case, which is still fine for `n <= 2000`.↵
</spoiler>↵
↵
## Problem-D:[problem:734480D]↵
**Tags:** `Trees` `Implementation` `Counting`<br>↵
**Difficulty:** ⭐⭐ (Easy)↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
You are given a **rooted tree** with `n` vertices. The root is vertex `1`. For every vertex `i >= 2` you are given its parent `p_i`.  ↵
↵
A tree is called a **spruce** if **every non-leaf vertex has at least 3 leaf children**.  ↵
↵
A **leaf** is a vertex with no children. Print `Yes` if the tree is a spruce and `No` otherwise.↵
↵
---↵
↵
#### Input Constraints↵
$$3 \le n \le 1000$$  ↵
The `n-1` lines contain `p_2, ..., p_n`.↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- First build, for every vertex, the **list of its children**.  ↵
- A vertex is a leaf exactly when its list is empty.  ↵
- Then just check the rule for **every** vertex that is not a leaf.↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Step 1: Build the children lists↵
Read the parents and do `children[p].append(i)`. Now we know the tree explicitly.↵
↵
### Step 2: Check the condition↵
For every vertex `v`:↵
- If `children[v]` is empty, `v` is a leaf. Nothing to check.  ↵
- Otherwise count how many children `c` of `v` are leaves (`children[c]` is empty). If this count is **less than 3**, the tree is not a spruce -> print `No`.↵
↵
If no vertex fails, print `Yes`.↵
↵
---↵
↵
### Example↵
Parents: `1 1 1 2 2 2` (n = 7).  ↵
Vertex 1 has children `2, 3, 4`. Vertices `3` and `4` are leaves, but `2` is not (it has children `5, 6, 7`), so vertex 1 has only **2** leaf children -> `No`.↵
↵
---↵
↵
### Common Pitfalls↵
- **Root with 2 children is not a spruce**, even if everything below looks perfect.  ↵
- Do not count *all* children: only the **leaf** children count.  ↵
- The check is for every non-leaf vertex, including the root.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    n = int(data[0])↵
    children = [[] for _ in range(n + 1)]↵
    for i in range(2, n + 1):↵
        p = int(data[i - 1])↵
        children[p].append(i)↵
↵
    def is_leaf(v):↵
        return len(children[v]) == 0↵
↵
    for v in range(1, n + 1):↵
        if not is_leaf(v):↵
            leaf_kids = sum(1 for c in children[v] if is_leaf(c))↵
            if leaf_kids < 3:↵
                print("No")↵
                return↵
    print("Yes")↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(n). Each child is looked at once from its parent.  ↵
- **Space:** O(n) for the children lists.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Count leaves with one array">↵
**Topic:** Counting  ↵
↵
A vertex `v` appears as a parent exactly `len(children[v])` times. So:↵
↵
1. `kids[v]` = number of times `v` appears in the parent list. `v` is a leaf if `kids[v] == 0`.  ↵
2. For every `i >= 2` with `kids[i] == 0` do `leaf_kids[p_i] += 1`.  ↵
3. Answer is `Yes` iff `kids[v] == 0 or leaf_kids[v] >= 3` for all `v`.↵
↵
Same complexity, no list of lists needed.↵
</spoiler>↵
↵
## Problem-E:[problem:734480E]↵
**Tags:** `Trees` `Constructive`<br>↵
**Difficulty:** ⭐⭐⭐ (Medium)↵
↵
A constructive problem: you must **build a tree** that satisfies all the conditions. Any valid tree is accepted.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Goal↵
You are given `n` vertices and `m` restrictions `(a, b, c)`. For every restriction the **simple path from `a` to `c` must NOT pass through `b`**.  ↵
↵
Build any tree on the vertices `1..n` (print `n-1` edges) that satisfies all restrictions. It is guaranteed that an answer exists.↵
↵
---↵
↵
#### Input↵
- `t` test cases.  ↵
- Each test: `n`, `m`, then `m` lines `a b c` with `a, b, c` pairwise different.  ↵
- `3 <= n <= 10^5`, `1 <= m < n`  ↵
↵
#### Output↵
`n-1` lines, each with two vertices `u v` (an edge of the tree).↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- Which vertices are **dangerous**? Only the vertices that appear as the middle value `b` of some restriction.  ↵
- Since `m < n`, there are at most `m` dangerous vertices, so at least one vertex is **not** dangerous. ↵
- Which tree shape makes *every* path pass through very few vertices?↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Idea: use a star↵
In a **star** with center `x`, every vertex is connected directly to `x`. The path between two different leaves `u` and `v` is `u -> x -> v`, so it only contains `u`, `x` and `v`. A path starting or ending at `x` is just one edge.↵
↵
So in a star centered at `x`, a path from `a` to `c` can contain **only `a`, `c` and `x`**.  ↵
↵
We need `b` to never be on it. Since `b != a` and `b != c`, the only danger is `b = x`.  ↵
↵
> Choose the center `x` to be a vertex that **never appears as `b`** in any restriction.↵
↵
---↵
↵
### Why such a vertex exists↵
There are `m` restrictions, so at most `m` different values of `b`. Because `m < n`, at least one of the `n` vertices is never used as `b`. ↵
↵
---↵
↵
### Algorithm↵
1. Mark every `b` from the input in a boolean array `forbidden`.  ↵
2. Take any `x` with `forbidden[x] == False`.  ↵
3. Print the edges `x v` for every `v != x`.↵
↵
---↵
↵
### Common Pitfalls↵
- You must read **all** restrictions before choosing the center.  ↵
- The output must contain exactly `n-1` edges.  ↵
- The center is allowed to be `a` or `c` of some restriction. That is fine, because then the path is a single edge that does not contain `b`.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    t = int(data[0]); pos = 1↵
    out = []↵
    for _ in range(t):↵
        n, m = int(data[pos]), int(data[pos + 1]); pos += 2↵
        forbidden = [False] * (n + 1)↵
        for _ in range(m):↵
            b = int(data[pos + 1])      # a = data[pos], c = data[pos + 2]↵
            forbidden[b] = True↵
            pos += 3↵
        center = 1↵
        for v in range(1, n + 1):↵
            if not forbidden[v]:↵
                center = v↵
                break↵
        for v in range(1, n + 1):↵
            if v != center:↵
                out.append(f"{center} {v}")↵
    print("\n".join(out))↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(n + m) per test case.  ↵
- **Space:** O(n).↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Think of it as a tree with one special vertex">↵
**Topic:** Trees  ↵
↵
You can also see the answer as a rooted tree: the safe vertex `x` is the **root** and every other vertex is a **leaf child** of the root (depth 1). The only property we use is *"`b` is never an internal vertex of a path"*, and in this tree the only internal vertex of any path is the root. Choosing the **smallest** or the **largest** safe vertex as root are both fine, because the checker accepts every valid tree.↵
</spoiler>↵
↵
## Problem-F:[problem:734480F]↵
**Tags:** `Recursion` `Backtracking` `Brute Force` `Strings`<br>↵
**Difficulty:** ⭐⭐⭐ (Medium)↵
↵
This is a pure **recursion / backtracking** problem: the constraints are tiny, so we simply try everything.↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Story↵
Limak has a string of length `n` using only the letters `a, b, c, d, e, f`.  ↵
↵
You are given `q` operations. Each operation is a pair `(a_i, b_i)`, where `a_i` is a string of **length 2** and `b_i` is a **single letter**. An operation can be used if the **first two letters** of the current string are exactly `a_i`; those two letters are replaced by `b_i` (the string becomes one letter shorter).  ↵
↵
All the `a_i` are **different**.  ↵
↵
Count how many starting strings of length `n` can be **compressed to the single letter `a`** by performing exactly `n-1` operations.↵
↵
---↵
↵
#### Example↵
`n = 3`, operations: `ab -> a`, `cc -> c`, `ca -> a`, `ee -> c`, `ff -> d`.  ↵
The valid starting strings are `abb`, `cab`, `cca`, `eea`. Answer: `4`.↵
↵
---↵
↵
#### Input Constraints↵
$$2 \le n \le 6,\qquad 1 \le q \le 36$$↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- How many strings of length `n` exist at all? `6^n <= 6^6 = 46656`. That is tiny!  ↵
- For one fixed string, is there any real choice during the compression, or is every step forced?  ↵
- Write a function `can_reach_a(s)` that works on strings of any length.↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Step 1: Generate every string (recursion)↵
We build strings letter by letter:↵
↵
- **Base case:** the string has length `n` -> test it.  ↵
- **Recursive case:** append each of the six letters and recurse.↵
↵
This visits at most `6 + 6^2 + ... + 6^6` strings, around 56 thousand.↵
↵
---↵
↵
### Step 2: Test one string (recursion)↵
An operation always works on the **first two** letters, so there is **no choice** to make: at each step at most one operation applies. ↵
↵
`can_reach_a(s)`:↵
- **Base case:** if `len(s) == 1`, return `s == "a"`.  ↵
- If the first two letters are not the left side of any operation -> return `False` (dead end).  ↵
- **Recursive case:** replace them using the matching operation and return `can_reach_a(new_string)`.↵
↵
We store the operations in a dictionary `rule[a_i] = b_i` so that the lookup is `O(1)`.↵
↵
---↵
↵
### Why this is fast↵
For one string we do at most `n-1 <= 5` steps. Total work is about `46656 * 5`, which is instant.↵
↵
---↵
↵
### Common Pitfalls↵
- The operation is applied to the **first two** letters only (not to any adjacent pair).  ↵
- You must perform **exactly `n-1` operations**, i.e. end with a string of length 1. If you get stuck earlier, that string does not count.  ↵
- Count strings, not sequences of operations.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    n, q = int(data[0]), int(data[1])↵
    rule = {}↵
    for i in range(q):↵
        rule[data[2 + 2 * i]] = data[3 + 2 * i]↵
↵
    def can_reach_a(s):↵
        if len(s) == 1:                       # base case↵
            return s == "a"↵
        pair = s[:2]↵
        if pair not in rule:                  # no operation applies: dead end↵
            return False↵
        return can_reach_a(rule[pair] + s[2:])   # recursive case: compress once↵
↵
    count = 0↵
    letters = "abcdef"↵
↵
    def build(s):↵
        nonlocal count↵
        if len(s) == n:↵
            if can_reach_a(s):↵
                count += 1↵
            return↵
        for ch in letters:↵
            build(s + ch)↵
↵
    build("")↵
    print(count)↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(6^n * n) = about `46656 * 6` operations in the worst case.  ↵
- **Space:** O(n) recursion depth plus the rule table.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Run it backwards">↵
**Topic:** Backtracking (reverse)  ↵
↵
Instead of trying every start string, start from the answer `"a"` and **undo** operations. Undoing `a_i -> b_i` means: if the first letter is `b_i`, replace it with the two letters `a_i`. Every start string that works is created by exactly `n-1` undo steps, and we only create strings that are useful:↵
↵
~~~~~↵
import sys↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    n, q = int(data[0]), int(data[1])↵
    rules = [(data[2 + 2 * i], data[3 + 2 * i]) for i in range(q)]↵
↵
    def expand(s, length):↵
        # s is a string that compresses to "a"; undo one operation at a time↵
        if length == n:↵
            return {s}↵
        result = set()↵
        for ai, bi in rules:↵
            if s[0] == bi:                       # the first letter was produced by this rule↵
                result |= expand(ai + s[1:], length + 1)↵
        return result↵
↵
    print(len(expand("a", 1)))↵
↵
main()↵
~~~~~↵
↵
We use a `set` because different undo sequences can produce the same string. The result is the same, but we never even look at the strings that can't be compressed to `a`.↵
</spoiler>↵
↵
## Problem-G:[problem:734480G]↵
**Tags:** `Trees` `DFS` `Dynamic Programming` `Recursion`<br>↵
**Difficulty:** ⭐⭐⭐⭐ (Hard)↵
↵
The hardest problem of the set, but it follows the exact pattern we learned in the Trees lectures: compute a value **from the children up** (post-order), then push another value **from the parent down** (pre-order).↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Story↵
There is a binary tree with `n+1` vertices numbered `0 .. n`. The root is vertex `0`; vertex `0` has exactly one child, vertex `1`. Every other vertex has either **0 children** (a leaf) or **exactly 2 children** (left and right).  ↵
↵
Bob walks in the tree and wants to reach vertex `0`. At the start nothing is written on any vertex. When Bob is on vertex `v` (`1 <= v <= n`):↵
↵
1. If `v` is a **leaf**: move to the parent.  ↵
2. Else if **nothing** is written on `v`: write `L` on `v` and move to the **left** child.  ↵
3. Else if `L` is written on `v`: overwrite it with `R` and move to the **right** child.  ↵
4. Else (`R` is written): erase it and move to the **parent**.  ↵
↵
Each move costs 1 second. For every `k = 1..n`, find the time to reach vertex `0` if Bob **starts at `k`**, modulo `10^9+7`.↵
↵
---↵
↵
#### Input↵
- `t` test cases. Each has `n` (odd, `n <= 300001`) followed by `n` lines `l_i r_i` for vertices `1..n` (`0 0` for a leaf).  ↵
- Sum of `n` over all tests `<= 300001`.↵
↵
#### Example↵
For the tree `1 -> (2, 3)`, `3 -> (4, 5)` (so `n = 5`) the answers are `9 10 14 15 15`. From vertex `3` the walk takes 14 seconds.↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- Look at what Bob does inside one subtree: he enters it with everything blank and, when he leaves, **everything is blank again**. So the time to explore a subtree depends only on the subtree itself.  ↵
- Let `dp[v]` be the time from standing on `v` (blank subtree) until Bob steps to the parent. Write `dp[v]` using `dp[left]` and `dp[right]`.  ↵
- If Bob starts at `k`, all its ancestors are blank. What happens right after he first reaches the parent?↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Step 1: Time to finish one subtree↵
Let `dp[v]` = the number of seconds from the moment Bob stands on `v` (with the subtree below `v` blank) until the moment he **moves up to the parent of `v`**. When he comes back up, the subtree is blank again (every `R` was erased).↵
↵
- **Base case (leaf):** one move up -> `dp[v] = 1`.  ↵
- **Recursive case:** for a vertex with children `l` and `r`:↵
  1. move down to `l` (1 s), then spend `dp[l]` to finish `l` and come back,  ↵
  2. now `v` has `L` -> move down to `r` (1 s), spend `dp[r]`,  ↵
  3. now `v` has `R` -> erase it and move up (1 s).  ↵
↵
$$dp[v] = dp[l] + dp[r] + 3$$↵
↵
This is exactly the post-order pattern: *solve both children first, then combine*.↵
↵
---↵
↵
### Step 2: Starting at `k`↵
All vertices are blank at the beginning. Starting at `k`, Bob spends `dp[k]` seconds to reach the parent `p` of `k`. **Now `p` is blank** (he never wrote anything there because he did not come from `p`), exactly as if he had started at `p`. So:↵
↵
$$\tau_k = dp[k] + \tau_{p}$$↵
↵
with `tau` of vertex `1` equal to `dp[1]` (its parent is the exit vertex `0`).↵
↵
This is the pre-order pattern: *the parent's answer is known before the children's*.↵
↵
---↵
↵
### Check with the example↵
Leaves `2, 4, 5` have `dp = 1`. `dp[3] = 1 + 1 + 3 = 5`, `dp[1] = 1 + 5 + 3 = 9`.  ↵
`tau_1 = 9`, `tau_2 = 1 + 9 = 10`, `tau_3 = 5 + 9 = 14`, `tau_4 = tau_5 = 1 + 14 = 15`. ✓↵
↵
---↵
↵
### Implementation notes↵
- The tree can be a long path (depth about `150000`), which would overflow Python's recursion stack. We therefore use an **explicit stack** (the iterative version of the DFS from the slides) to get a preorder list. Processing that list **backwards** gives the post-order for `dp`, and processing it **forwards** gives the pre-order for `tau`.  ↵
- Do everything modulo `10^9+7`.  ↵
- Use fast input (`sys.stdin.read().split()`), since there are up to `300001` lines.↵
↵
---↵
↵
### Common Pitfalls↵
- The values grow exponentially along a path, so the modulo is required at every addition.  ↵
- Do not forget that `tau[1] = dp[1]` (not `dp[1] + something`).↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    MOD = 10**9 + 7↵
    t = int(data[0]); pos = 1↵
    out = []↵
    for _ in range(t):↵
        n = int(data[pos]); pos += 1↵
        left = [0] * (n + 1)↵
        right = [0] * (n + 1)↵
        for i in range(1, n + 1):↵
            left[i] = int(data[pos]); right[i] = int(data[pos + 1]); pos += 2↵
↵
        # preorder with an explicit stack (the iterative version of DFS)↵
        order = []↵
        stack = [1]↵
        while stack:↵
            v = stack.pop()↵
            order.append(v)↵
            if left[v] != 0:↵
                stack.append(left[v])↵
                stack.append(right[v])↵
↵
        # dp[v] = seconds to go from v (all blank below) until Bob steps up to the parent↵
        dp = [0] * (n + 1)↵
        for v in reversed(order):                 # children are processed before parents↵
            if left[v] == 0:↵
                dp[v] = 1↵
            else:↵
                dp[v] = (dp[left[v]] + dp[right[v]] + 3) % MOD↵
↵
        # tau[v] = dp[v] + tau[parent]; vertex 1's parent is 0, which costs nothing more↵
        tau = [0] * (n + 1)↵
        tau[1] = dp[1]↵
        for v in order:↵
            if left[v] != 0:↵
                tau[left[v]] = (dp[left[v]] + tau[v]) % MOD↵
                tau[right[v]] = (dp[right[v]] + tau[v]) % MOD↵
↵
        out.append(" ".join(map(str, tau[1:])))↵
    print("\n".join(out))↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** O(n). Each vertex is visited a constant number of times.  ↵
- **Space:** O(n) for `left`, `right`, `dp`, `tau` and the stack.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Plain recursion (two DFS functions)">↵
**Topic:** Recursion  ↵
↵
This is the same solution written with real recursion. In Python it needs a big thread stack because the tree can be very deep:↵
↵
~~~~~↵
import sys, threading↵
↵
def main():↵
    data = sys.stdin.read().split()↵
    MOD = 10**9 + 7↵
    t = int(data[0]); pos = 1↵
    out = []↵
    for _ in range(t):↵
        n = int(data[pos]); pos += 1↵
        left = [0] * (n + 1); right = [0] * (n + 1)↵
        for i in range(1, n + 1):↵
            left[i] = int(data[pos]); right[i] = int(data[pos + 1]); pos += 2↵
        dp = [0] * (n + 1)↵
        tau = [0] * (n + 1)↵
↵
        def go_down(v):                      # post-order: children first↵
            if left[v] == 0:↵
                dp[v] = 1↵
            else:↵
                dp[v] = (go_down(left[v]) + go_down(right[v]) + 3) % MOD↵
            return dp[v]↵
↵
        def go_up(v, from_parent):           # pre-order: parent's answer is ready↵
            tau[v] = (dp[v] + from_parent) % MOD↵
            if left[v] != 0:↵
                go_up(left[v], tau[v])↵
                go_up(right[v], tau[v])↵
↵
        go_down(1)↵
        go_up(1, 0)↵
        out.append(" ".join(map(str, tau[1:])))↵
    print("\n".join(out))↵
↵
sys.setrecursionlimit(1 << 20)↵
threading.stack_size(512 * 1024 * 1024)↵
th = threading.Thread(target=main); th.start(); th.join()↵
~~~~~↵
↵
`go_down` is the post-order DFS that fills `dp`, and `go_up` is the pre-order DFS that fills `tau`. In C++ or Java the recursive version is usually enough without any tricks, but the iterative version above is safer in Python.↵
</spoiler>↵
↵
## Problem-H:[problem:734480H]↵
**Tags:** `Recursion` `Backtracking` `DFS` `Brute Force` `Implementation`<br>↵
**Difficulty:** ⭐⭐⭐ (Medium)↵
↵
<spoiler summary="Understanding the Problem">↵
↵
#### The Story↵
A positive integer is called **lucky** here if its decimal representation contains **at most two different digits**. For example `100`, `121`, and `7777` are lucky, but `123` and `1002` are not (they use three different digits).  ↵
↵
Given `n`, count how many positive integers `x` with `1 <= x <= n` are lucky.↵
↵
---↵
↵
#### Example↵
`n = 10` -> answer `10` (all numbers from 1 to 10).  ↵
`n = 123` -> answer `113`. The only numbers up to 123 that are **not** lucky are `102, 103, ..., 109` (8 numbers), `120` and `123`, so `123 - 10 = 113`.↵
↵
---↵
↵
#### Input Constraints↵
$$1 \le n \le 10^9$$↵
</spoiler>↵
↵
<spoiler summary="Hint">↵
- Looping over all numbers up to `10^9` is too slow.  ↵
- But the **lucky numbers are very few**: roughly `10^4` of them below `10^9`. Can you **generate only the lucky ones**?  ↵
- Build a number digit by digit. If a number is already not lucky, adding more digits will **never** make it lucky again. ↵
</spoiler>↵
↵
<spoiler summary="Tutorial">↵
### Idea: build numbers digit by digit with recursion↵
We create numbers by appending digits, and we only keep going while the number is still lucky.↵
↵
`dfs(num, digits)`: `num` is a lucky number built so far and `digits` is the set of digits it uses.↵
↵
For every digit `d` from `0` to `9`:↵
1. `nxt = num * 10 + d`.  ↵
2. If `nxt == 0`, skip it (no leading zeros).  ↵
3. If `nxt > n`, **stop the loop** (`break`): larger digits only make `nxt` larger.  ↵
4. Let `new_digits = digits ∪ {d}`. If it has **at most 2** digits, then `nxt` is lucky: count it and call `dfs(nxt, new_digits)`.  ↵
5. Otherwise this branch is dead, so we do not recurse (this is the *pruning* step of backtracking).↵
↵
We start with `dfs(0, empty set)`.↵
↵
---↵
↵
### Why each number is counted once↵
Every number has exactly one decimal representation, and we create it by exactly one sequence of appended digits (its own digits from left to right). So no duplicates and no `set` of results is needed.↵
↵
---↵
↵
### Why it is fast↵
The number of lucky numbers up to `10^9` is only about `40744` in the worst case, and we visit each of them once (plus at most ten failed tries from each). The recursion depth is at most `10`.↵
↵
---↵
↵
### Common Pitfalls↵
- Counting `0` or numbers with leading zeros (`07`) as lucky.  ↵
- Forgetting the `break` when `nxt > n` (not required for correctness, only speed).  ↵
- Forgetting to prune when a third different digit appears; without it the DFS visits all numbers.↵
</spoiler>↵
↵
<spoiler summary="Solution (Python)">↵
↵
~~~~~↵
import sys↵
sys.setrecursionlimit(10000)↵
↵
def main():↵
    n = int(input())↵
    count = 0↵
↵
    def dfs(num, digits):↵
        # num is already a valid lucky number (or 0 at the start); digits = set of used digits↵
        nonlocal count↵
        for d in range(10):↵
            nxt = num * 10 + d↵
            if nxt == 0:↵
                continue                 # no leading zeros↵
            if nxt > n:↵
                break                    # bigger d only makes nxt bigger↵
            new_digits = digits | {d}↵
            if len(new_digits) <= 2:↵
                count += 1↵
                dfs(nxt, new_digits)↵
↵
    dfs(0, frozenset())↵
    print(count)↵
↵
main()↵
~~~~~↵
↵
### Complexity:↵
- **Time:** about O(10 * L), where `L` is the number of lucky numbers up to `n` (at most about `4 * 10^4`).  ↵
- **Space:** O(log n): the recursion depth is the number of digits of `n`.↵
</spoiler>↵
↵
<spoiler summary="Alternative Approach: Choose the two digits first">↵
**Topic:** Brute Force + Recursion  ↵
↵
Iterate over every pair of digits `(x, y)` with `0 <= x <= y <= 9`. For each pair run a DFS that appends only `x` or `y`, collecting the numbers `<= n` into a Python `set`. The set removes duplicates (e.g. a number made only of `x` appears for many pairs). The answer is the size of the set.↵
↵
It is simpler to reason about, but needs a `set` and does about 55 separate DFS runs, so the main solution is a little cleaner.↵
</spoiler>↵
↵

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English ayanasamuel 2026-12-02 02:25:21 2 (published)
en1 English ayanasamuel 2026-12-02 02:20:09 36347 Initial revision (saved to drafts)