# 牛客第7场I-Valuable Forests prufer序列+DP

## 题意：

T ≤ 5000 , N ≤ 5000 T\leq 5000,N \leq 5000

## Solution:

f ( n ) = ∑ i = 0 n − 1 C n − 1 i f ( n − i − 1 ) ∗ s t ( i + 1 ) f(n)=\sum_{i=0}^{n-1}C_{n-1}^if(n-i-1)*st(i+1)

A ( n ) = ∑ i = 1 n ∑ d = 1 n − 1 d 2 C n − 2 d − 1 ∗ ( n − 1 ) ( n − 2 − d + 1 ) A(n)=\sum_{i=1}^n\sum_{d=1}^{n-1}d^2C_{n-2}^{d-1}*(n-1)^{(n-2-d+1)}

A ( n ) = n ∑ d = 1 n − 1 d 2 C n − 2 d − 1 ∗ ( n − 1 ) ( n − 2 − d + 1 ) A(n)=n\sum_{d=1}^{n-1}d^2C_{n-2}^{d-1}*(n-1)^{(n-2-d+1)} (比赛的时候没有发现…想了半天如何简化)

F ( n ) = ∑ i = 0 n − 1 C N − 1 i ∗ ( s t ( i + 1 ) ∗ F ( n − i − 1 ) + f ( n − i − 1 ) ∗ A ( i + 1 ) ) F(n)=\sum_{i=0}^{n-1}C_{N-1}^i*(st(i+1)*F(n-i-1)+f(n-i-1)*A(i+1))

## 代码：

#include<cstdio>
#include<iostream>
using namespace std;
int n,num[100010];
int a[100010];
int C[5010][5010],A[5010],F[5010],f[5010];
int st[5010];
int T,mod;
int fast_pow(int x,int a)
{
int ans=1;
for (;a;x=1ll*x*x%mod,a>>=1)
if (a&1) ans=1ll*ans*x%mod;
return ans;
}
int main()
{
scanf("%d%d",&T,&mod);
C[0][0]=1;
for (int i=1;i<=5000;i++)
{
C[0][i]=1;
for (int j=1;j<=i;j++)
C[j][i]=(1ll*C[j][i-1]+C[j-1][i-1])%mod;
}
st[0]=st[1]=1;
for (int N=1;N<=5000;N++)
{
for (int d=1;d<=N-1;d++)
{
A[N]=(1ll*d*d*C[d-1][N-2]%mod*fast_pow(N-1,N-2-d+1)+A[N])%mod;
}
A[N]=1ll*N*A[N]%mod;
if (N>1) st[N]=fast_pow(N,N-2);
}
f[0]=1;f[1]=1;
for (int i=2;i<=5000;i++)
{
for (int j=0;j<i;j++)
f[i]=(1ll*C[j][i-1]*f[i-j-1]%mod*st[j+1]+f[i])%mod;
}
for (int N=2;N<=5000;N++)
for (int i=1;i<=N;i++)
{
F[N]=(1ll*C[i-1][N-1]*((1ll*st[i]*F[N-i]%mod+1ll*f[N-i]*A[i]%mod)%mod)+F[N])%mod;
}
while (T--)
{
scanf("%d",&n);

printf("%d\n",F[n]);
}
}



07-28 114
08-07 58