题目链接:点我
题目
Figure 1 shows the Yang Hui Triangle. We number the row from top to bottom 0,1,2,…and the column from left to right 0,1,2,….If using C(n,k) represents the number of row n, column k. The Yang Hui Triangle has a regular pattern as follows.
C(n,0)=C(n,n)=1 (n ≥ 0)
C(n,k)=C(n-1,k-1)+C(n-1,k) (0<k<n)
Write a program that calculates the minimum sum of numbers passed on a route that starts at the top and ends at row n, column k. Each step can go either straight down or diagonally down to the right like figure 2.
As the answer may be very large, you only need to output the answer mod p which is a prime.
Input
Input to the problem will consists of series of up to 100000 data sets. For each data there is a line contains three integers n, k(0<=k<=n<10^9) p(p<10^4 and p is a prime) . Input is terminated by end-of-file.
Output
For every test case, you should output "Case #C: " first, where C indicates the case number and starts at 1.Then output the minimum sum mod p.
Sample Input
1 1 2
4 2 7
Sample Output
Case #1: 0
Case #2: 5
题意:
求杨辉三角的从顶部开始到坐标为(n, m)的数的和的最小值模p.
思路:
Lucas定理, 高中数学都教过杨辉三角的一个性质,那就是莫一斜列的数的和等于最后那个数的那么那个数,即是: C(m,1) + C(m+1,2) +…+C(m+k,n) = C(m+k+1, n+1);
并且这个值一个是满足题意的最小的值,所以这题我们可以先沿边界走到某个地方之后,我们开始斜着走,使斜着走的自小,那么和也一定最小.那么我们需要沿边界走多少呢,出图书可以看书,当剩下的m (或者当n/2 大于 m 时,我们从右边界走,此时m = n - m)等于 n时,得到的值最小,那么我们只需要走沿边界走m步即可.
代码:
1 |
|