题面戳这里
dp的姿势有两种(都保证了拆分的有序):
- (f_{i,j})表示拆分中最大数为(j),和为(i)的方案数。转移$$f_{i,j} = sum_{k = 1}^j f_{i-j,k}$$
然后可以用前缀和优化一下。复杂度(O(N^2)) - (f_{i,j})表示和为(i),拆分为(j)个数的方案数。转移这样考虑,要么在拆分方案中增加(1),要么把拆分中所有数增加(1)。方程如下
[f_{i,j} = f_{i-1,j-1}+f_{i-j,j}
]
然后由于这题数据范围比较大,我们需要滚动数组。其实有时第二维也可以滚动(将dp方程反过来看就行了)
import java.util.Scanner;
import java.math.BigInteger;
public class Main{
static int maxn = 5010,N;
static BigInteger f[][] = new BigInteger[2][maxn];
static BigInteger ans[] = new BigInteger[maxn];
public static void ready()
{
for (int j = 0;j < maxn;++j) f[0][j] = BigInteger.ZERO;
ans[0] = f[0][0] = BigInteger.ONE;
for (int j = 1;j <= 5000;++j)
{
int p = j&1,q = p^1;
f[p][0] = BigInteger.ONE;
for (int i = 1;i <= 5000;++i)
{
f[p][i] = f[q][i];
if (i-j >= 0) f[p][i] = f[p][i].add(f[p][i-j]);
}
ans[j] = f[p][j];
}
}
public static void main(String args[])
{
ready();
Scanner in = new Scanner(System.in);
while (in.hasNextInt())
{
N = in.nextInt();
System.out.println(ans[N]);
}
}
}