2 3 2 1 2 1 3 10 8 2 1 3 2 4 1 5 3 6 1 7 3 8 7 9 7 10 6
Case #1: 4 Case #2: 316512
f[i,j] 表示子树i有j个Leader 的方案数
f[i,j]=f[i-1,j]*p+f[i-1,j-1]*(1-p) (p=1/siz[i])
把概率用逆元算来确保精度,
逆元要预处理
#include<bits/stdc++.h> using namespace std; #define For(i,n) for(int i=1;i<=n;i++) #define Fork(i,k,n) for(int i=k;i<=n;i++) #define Rep(i,n) for(int i=0;i<n;i++) #define ForD(i,n) for(int i=n;i;i--) #define RepD(i,n) for(int i=n;i>=0;i--) #define Forp(x) for(int p=pre[x];p;p=Next[p]) #define Forpiter(x) for(int &p=iter[x];p;p=Next[p]) #define Lson (x<<1) #define Rson ((x<<1)+1) #define MEM(a) memset(a,0,sizeof(a)); #define MEMI(a) memset(a,127,sizeof(a)); #define MEMi(a) memset(a,128,sizeof(a)); #define INF (2139062143) #define F (1000000007) #define MAXN (1000+10) #define MAXM (2000+10) typedef long long ll; ll mul(ll a,ll b){return (a*b)%F;} ll add(ll a,ll b){return (a+b)%F;} ll sub(ll a,ll b){return (a-b+llabs(a-b)/F*F+F)%F;} void upd(ll &a,ll b){a=(a%F+b%F)%F;} ll f[MAXN][MAXN]; int n,K; int edge[MAXM],Next[MAXM],pre[MAXM],siz=1; void addedge(int u,int v) { edge[++siz]=v; Next[siz]=pre[u]; pre[u]=siz; } void addedge2(int u,int v) {addedge(u,v); addedge(v,u); } int sz[MAXN]; void dfs(int x,int fa){ Forp(x) { int v=edge[p]; if (v==fa) continue; dfs(v,x); sz[x]+=sz[v]; } sz[x]++; } int pow2(int a,int b) { if (b==0) return 1; if (b==1) return a; int t=pow2(a,b/2); t=mul(t,t); if (b&1) t=mul(t,a); return t; } int inv[MAXN]; int main() { // freopen("J.in","r",stdin); Rep(i,1001) inv[i]=pow2(i,F-2); int T;cin>>T; For(kcase,T) { scanf("%d%d",&n,&K); MEM(f) siz=1; MEM(pre) MEM(Next) MEM(edge) MEM(sz) For(i,n-1) { int u,v; scanf("%d%d",&u,&v); addedge2(u,v); } dfs(1,0); f[0][0]=1; For(i,n) { Rep(j,1+min(K,i)) f[i][j]=add(mul(mul(f[i-1][j],sz[i]-1),inv[sz[i]]),(j>0)?mul(f[i-1][j-1],inv[sz[i]] ) : 0 ); } ll ans=f[n][K]; For(i,n) ans=mul(ans,i); printf("Case #%d: %I64d\n",kcase,ans); } return 0; }