How do you add?
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 K numbers 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
Input
Each line will contain a pair of numbers N and K . N and K will both be an integer from 1 to 100, inclusive. The input will terminate on 2 0's.Output
Since Larry is only interested in the last few digits of the answer, for each pair of numbers N and K , print a single number mod 1,000,000 on a single line.Sample Input
20 2 20 2 0 0
Sample Output
21 21
译:
[Description] Larry 的数学非常不好,他经常使用计算器。不幸的是,他现在和他一个好朋友被困在一个 沙漠岛上。他们正试着通过解决一些好问题来消耗时间,而如果 Larry 不能答出问题,Ryan 就要吃掉他,所以他的命运掌握在你的手中! 这是一个很简单的问题:给出一个数字 N,用 K 个小于 N 的数加起来为 N,有多少张方法? 例如 N = 20, K = 2,就有 21 中方法: 0+20 1+19 2+18 3+17 4+16 5+15 ... 18+2 19+1 20+0 [Input] 对于每组数据一行两个整数 N 和 K 直到 N = K = 0 时输入结束 [Output] 对于每组数据,输出答案对 1,000,000 取模后的结果 [Sample Input] 20 2 20 2 0 0 [Sample Output] 21 21 [Hint] 1 <= N, K <= 100
/*刚看时觉得比较麻烦但是画表分析下就.......
dp[n][k]
dp[1][1]=1 | dp[2][1]=1 | dp[3][1]=1 | dp[4][1]=1 | dp[5][1]=1 |
dp[1][2]=2 | dp[2][2]=3 | dp[3][2]=4 | ... | ... |
dp[1][3]=3 | dp[2][3]=6 | dp[3][3]=10 | ... | ... |
dp[1][4]=4 | ... | ... | ... | .. |
把表列出来后会有惊奇的发现
上代码了
#include<iostream> #include<cstdio> #include<cstring> #define mo 1000000 using namespace std; /* dp[i][j]表示用j个数加起来为i的方法数; dp[i][j]=dp[i-1][j]+dp[i][j-1]; 边界:dp[i][1]=1;dp[1][j]=j; */ int dp[120][120]; int n,k; int main() { for(int i=1;i<=100;i++)dp[i][1]=1; for(int i=1;i<=100;i++)dp[1][i]=i; for(int i=2;i<=100;i++) for(int j=2;j<=100;j++) { dp[i][j]=(dp[i-1][j]%mo+dp[i][j-1]%mo)%mo; } while(1) { scanf("%d%d",&n,&k); if(n==0&&k==0)break; printf("%d\n",dp[n][k]); } return 0; }