# k-Tree

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

Each sequence of edge weights specifies one path from the root. Let $C_r(s)$ count the paths of total weight $s$ when each edge has weight at most $r$. The empty path gives $C_r(0)=1$, and $C_r(s)=0$ for $s<0$. Removing the last edge of weight $i$ leaves total weight $s-i$, so for $s>0$,

$$
C_r(s)=\sum_{i=1}^{r}C_r(s-i).
$$

Evaluate the recurrence up to $n$ for $r=k$ and $r=d-1$. Subtracting the paths whose weights all fall below $d$ gives $C_k(n)-C_{d-1}(n)$. Reduce each sum and the final difference modulo $10^9+7$. Filling the tables in increasing order of $s$ takes $O(nk)$ time and $O(n)$ space.

For $n=3$, $k=3$, and $d=2$, the qualifying weight sequences are $(3)$, $(1,2)$, and $(2,1)$. The answer is $3$.

## 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) · [Editorial](https://xyzmaths.org/pow/k-tree/editorial/index.md)
