k-Tree
· Codeforces 431C
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 As count all paths of total weight s using weights from 1 to k. Let Bs count paths of the same total using only weights from 1 to d−1. Every path counted by As either uses an edge of weight at least d or belongs to Bs. The answer is therefore An−Bn.
Count paths by their final edge
There is one empty path, so A0=B0=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
AsBs=i=1∑kAs−i,=i=1∑d−1Bs−i.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 Bs=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=109+7 and add M before reducing the final difference so the printed residue is nonnegative.
C++ implementation
#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';
}