DP?
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 128000/128000 K (Java/Others)
Total Submission(s): 1930 Accepted Submission(s): 640
Problem Description
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
Sample Output
Author
phyxnj@UESTC
题意:告诉你在一个在杨辉三角中的点,问你从走到0,0点做到该店经过的点最少的权值和,而且只能走向下和,斜向下两个方向。
思路:容易看出,根据已知的那个点(n,m) 如果 n > 2*m 那么从已知点出发,可以一直往斜的方向走,直到边界,那么 权值和就为 C(n,m)+C(n-1,m-1)....... 由帕斯卡公式可得该式等于 C(n+1,m)+(n-m) 如果n <= 2*m,那么就是一直往上走,权值和就为C(n,m)+C(n-1,m)+C(n-2,m)..... 等于C(n+1,m+1)+m
得到公式之后因为n,m很大,所以需要用Lucas定理化简,而且样例有1e5组,因此要先将素数的一些组合数打好表。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int n,m,p;
const int maxn = 10000+10;
bool isPrime[maxn];
int CC[maxn][maxn];
int AA[maxn][maxn];
void gcd(int a,int b,int &d,int &x,int &y){
if(!b){
d = a;
x = 1;
y = 0;
}else{
gcd(b,a%b,d,y,x);
y -= x*(a/b);
}
}
inline int inv(int a,int p){
int d,x,y;
gcd(a,p,d,x,y);
return (d==1)?(x+p)%p:-1;
}
inline int C(int nn,int mm){
int ans;
if(nn<mm) return 0;
if(nn==mm||mm==0) return 1;
if(mm==1||mm==nn-1) return nn;
ans = (((AA[p][nn]*CC[p][mm])%p)*CC[p][nn-mm])%p;
return ans;
}
int Lucas(int nn,int mm){
if(mm==0) return 1;
int k = C(nn%p,mm%p);
return (k*Lucas(nn/p,mm/p))%p;
}
void init(){
memset(isPrime,1,sizeof isPrime);
int id = 0;
for(int i = 2; i < maxn; i++){
if(isPrime[i]){
CC[i][2] = inv(2,i);
for(int j = 3; j < i; j++){
CC[i][j] = (CC[i][j-1]*inv(j,i))%i;
}
for(int j = i*i; j < maxn; j+=i){
isPrime[j] = 0;
}
AA[i][1] = 1;
for(int j = 2; j < i; j++){
AA[i][j] = (AA[i][j-1]*j)%i;
}
}
}
}
int main(){
int T = 1;
init();
while(scanf("%d%d%d",&n,&m,&p) != EOF){
if(2*m < n)
printf("Case #%d: %d\n",T++,(Lucas(n+1,m)+n-m)%p);
else
printf("Case #%d: %d\n",T++,(Lucas(n+1,m+1)+m)%p);
}
return 0;
}
HDU3944-DP?(帕斯卡公式+Lucas定理),布布扣,bubuko.com
HDU3944-DP?(帕斯卡公式+Lucas定理)
原文:http://blog.csdn.net/mowayao/article/details/38493489