http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_problem&problem=1884
Larry is very bad at math - he usually uses a calculator, which worked well throughout college. Unforunately, he is now struck in a deserted island with his good buddy Ryan after a snowboarding accident. They're now trying to spend some time figuring out some good problems, and Ryan will eat Larry if he cannot answer, so his fate is up to you!
It's a very simple problem - given a number N, how many ways can Knumbers less than N add up to N?
For example, for N = 20 and K = 2, there are 21 ways:
0+20
1+19
2+18
3+17
4+16
5+15
...
18+2
19+1
20+0
20 2 20 2 0 0
21 21
首先题目的描述并不完整,本意是求:把N分解成K个非负整数有多少种分法。
思路:
1. 如何转化这一问题?——小球模型
这个问题可以等效成有N个相同的小球放到K个不同的盒子里,每个盒子可以为空,求一共多少种放置的方法。
2. 用何种方法求解?
可以这样理解, 我们把N个球用细线连成一排,再用K-1把刀去砍断细线,就可以把N个球按顺序分为K组(即分装到K个盒子中)。则N个球装入K个盒子的每一种装法都对应一种砍线的方法。而砍线的方法等于N个球与K-1把刀的排列方式。(注意可以让多把刀砍一根线)
故排列方法共有C(N+K-1,K-1)=C(N+K-1,N)种。
3. 如何计算?
由于要取模的原因,利用加法公式C(n+1,k+1)=C(n,k)+C(n,k+1)可以通过类似DP的递推形式求得结果。
完整代码:
/*0.012s*/ #include <cstdio> using namespace std; const int mod = 1000000; int dp[101][101]; int main(void) { int i, j, n, k; for (i = 1; i <= 100; i++) dp[1][i] = 1; for (j = 2; j <= 100; j++) { dp[j][1] = j; for (i = 2; i <= 100; i++) dp[j][i] = (dp[j - 1][i] + dp[j][i - 1]) % mod;///公式做了一些变形 } while (scanf("%d%d", &n, &k), n) printf("%d\n", dp[k][n]); return 0; }