k-Tree
· Codeforces 431C
Each sequence of edge weights specifies one path from the root. Let Cr(s) count the paths of total weight s when each edge has weight at most r. The empty path gives Cr(0)=1, and Cr(s)=0 for s<0. Removing the last edge of weight i leaves total weight s−i, so for s>0,
Cr(s)=i=1∑rCr(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 Ck(n)−Cd−1(n). Reduce each sum and the final difference modulo 109+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
#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';
}