dp[ i ][ j ]表示 i 这棵子树填满, 有 j 个满足条件的方案数。
转移的时候组合数乘一乘。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 1000 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T &a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T &a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T &a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T &a, S b) {return a > b ? a = b, true : false;} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int n, k, C[N][N]; int dp[N][N]; int tmp[N]; int sz[N]; vector<int> G[N]; void dfs(int u, int fa) { sz[u] = 1; int comb = 1; for(auto &v : G[u]) { if(v == fa) continue; dfs(v, u); sz[u] += sz[v]; } int nowsz = sz[u] - 1; for(auto &v : G[u]) { if(v == fa) continue; comb = 1LL * comb * C[nowsz][sz[v]] % mod; nowsz -= sz[v]; } memset(tmp, 0, sizeof(tmp)); tmp[0] = 1; nowsz = 0; for(auto &v : G[u]) { if(v == fa) continue; for(int i = nowsz; i >= 0; i--) { for(int j = 1; j <= sz[v]; j++) { if(i + j > k) break; add(tmp[i + j], 1LL * tmp[i] * dp[v][j] % mod); } tmp[i] = 0; } nowsz += sz[v]; } for(int i = 1; i <= min(sz[u], k); i++) { dp[u][i] = 1LL * tmp[i] * comb % mod * (sz[u] - 1) % mod; } for(int i = min(sz[u], k) - 1; i >= 0; i--) { add(dp[u][i + 1], 1LL * tmp[i] * comb % mod); } } void init() { for(int i = 1; i <= n; i++) { G[i].clear(); } } int main() { for(int i = 0; i < N; i++) { for(int j = C[i][0] = 1; j <= i; j++) { C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod; } } int T; scanf("%d", &T); for(int cas = 1; cas <= T; cas++) { scanf("%d%d", &n, &k); init(); for(int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); } dfs(1, 0); printf("Case #%d: %d\n", cas, dp[1][k]); } return 0; } /* */