# k-Tree

Editorial · 7 July 2026 · [Codeforces 431C](https://codeforces.com/problemset/problem/431/C)

The tree is infinite, but we can describe a path just by listing its edge weights in order. Once we know the next weight, there is exactly one child we can move to. For example, $(1,2)$ and $(2,1)$ lead to different vertices even though both paths have total weight $3$.

The threshold on the largest edge suggests counting the paths we should discard. Let $A_s$ count all paths of total weight $s$ using weights from $1$ to $k$. Let $B_s$ count paths of the same total using only weights from $1$ to $d-1$. Every path counted by $A_s$ either uses an edge of weight at least $d$ or belongs to $B_s$. The answer is therefore $A_n-B_n$.

## Count paths by their final edge

There is one empty path, so $A_0=B_0=1$. Set both counts to zero for negative totals. If a path of weight $s>0$ ends in an edge of weight $i$, removing that edge leaves a path of weight $s-i$. Conversely, each path of weight $s-i$ has exactly one extension by an edge of weight $i$. Grouping paths by that final weight gives

$$
\begin{aligned}
A_s &= \sum_{i=1}^{k} A_{s-i},\\
B_s &= \sum_{i=1}^{d-1} B_{s-i}.
\end{aligned}
$$

Both sums use smaller totals, so we can fill a table in increasing order of $s$. The same function computes either table when given its largest permitted weight. If $d=1$, the second sum is empty and $B_s=0$ for every positive $s$, as every nonempty path already qualifies.

## Worked example

Take $n=3$, $k=3$, and $d=2$. The four paths of total weight $3$ have weight lists $(1,1,1)$, $(1,2)$, $(2,1)$, and $(3)$. Only $(1,1,1)$ uses weights strictly below $2$. Subtracting it leaves $4-1=3$ qualifying paths.

## Time and space

Each table has $n+1$ entries and each entry sums at most $k$ earlier values. The two calls together take $O(nk)$ time and use $O(n)$ auxiliary space. We reduce each addition modulo $M=10^9+7$ and add $M$ before reducing the final difference so the printed residue is nonnegative.

## C++ implementation

```cpp
#include <iostream>
#include <vector>

constexpr long long modulus = 1'000'000'007;

long long count_paths(int target, int largest_weight) {
    std::vector<long long> ways(target + 1, 0);
    ways[0] = 1;

    for (int total = 1; total <= target; ++total) {
        for (int weight = 1; weight <= largest_weight && weight <= total; ++weight) {
            ways[total] = (ways[total] + ways[total - weight]) % modulus;
        }
    }
    return ways[target];
}

int main() {
    int n, k, d;
    if (!(std::cin >> n >> k >> d)) return 1;

    const long long all = count_paths(n, k);
    const long long small = count_paths(n, d - 1);
    std::cout << (all - small + modulus) % modulus << '\n';
}
```

[Problem](https://xyzmaths.org/pow/k-tree/index.md) · [Solution](https://xyzmaths.org/pow/k-tree/solution/index.md)
