状态转移很好想。。。。但是复杂度并不好证明。。。但是确实是n^2的算法。。。
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int maxn = 1005; const int maxm = 20005; const int mod = 1000000007; struct Edge { int v; Edge *next; }E[maxm], *H[maxn], *edges; LL f[maxn]; LL g[maxn]; LL dp[maxn][maxn]; LL a[maxn]; int size[maxn]; int tot[maxn]; int n, K; LL powmod(LL a, LL b) { LL base = a, res = 1; while(b) { if(b % 2) res = res * base % mod; base = base * base % mod; b /= 2; } return res; } void addedges(int u, int v) { edges->v = v; edges->next = H[u]; H[u] = edges++; } void init() { edges = E; memset(H, 0, sizeof H); memset(dp, 0, sizeof dp); memset(tot, 0, sizeof tot); } LL C(int n, int m) { if(m > n) return 0; return f[n] * g[m] % mod * g[n - m] % mod; } void dfs(int u, int fa) { dp[u][0] = 1; tot[u] = 1; size[u] = 0; for(Edge *e = H[u]; e; e = e->next) if(e->v != fa) { int v = e->v; dfs(v, u); for(int i = 0; i <= tot[u] + tot[v]; i++) a[i] = 0; LL t = C(size[u]+size[v], size[v]); for(int i = tot[u]; i >= 0; i--) { for(int j = tot[v]; j >= 1; j--) { a[i+j] = (a[i+j] + t * dp[u][i] % mod * dp[v][j] % mod) % mod; } } size[u] += size[v]; tot[u] += tot[v]; tot[u] = min(tot[u], K); for(int i = 0; i <= tot[u]; i++) dp[u][i] = a[i]; } for(int i = 0; i <= tot[u] + 1; i++) a[i] = 0; for(int i = tot[u]; i >= 0; i--) { a[i] = (a[i] + size[u] * dp[u][i]) % mod; a[i+1] = (a[i+1] + dp[u][i]) % mod; } tot[u]++; size[u]++; for(int i = 0; i <= tot[u]; i++) dp[u][i] = a[i]; } void work() { int u, v; scanf("%d%d", &n, &K); for(int i = 1; i < n; i++) { scanf("%d%d", &u, &v); addedges(u, v); addedges(v, u); } dfs(1, 1); printf("%lld\n", dp[1][K]); } int main() { f[0] = 1; for(int i = 1; i <= 1000; i++) f[i] = f[i-1] * i % mod; g[1000] = powmod(f[1000], mod - 2); for(int i = 999; i >= 0; i--) g[i] = g[i+1] * (i + 1) % mod; int _; scanf("%d", &_); for(int i = 1; i <= _; i++) { printf("Case #%d: ", i); init(); work(); } return 0; }