帕斯卡公式+Lucas定理______DP?( hdu 3944 )

来源:互联网 发布:万网怎么配置端口 编辑:程序博客网 时间:2024/04/27 17:52

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
1 1 24 2 7
 

Sample Output
Case #1: 0Case #2: 5
 



题意:给个n,k,问从第一行第一列走到第n行,第k列的最小路径点权和是多少? 只能向下走或者斜右下走。输出对p取模。


分析:

我们思考逆问题,从n,k走向1,1只能向上或者左上走。

容易看出,根据已知的那个点(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<stdio.h>#include<string.h>typedef long long ll;int book[10000] ={1,1,0};int prim[10000],pnum = 0;int preC[1300][10001],preA[1300][10001];int s[2001];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;}void init(){    for(int i = 2 ; i < 10000 ; i ++)    {        if(book[i])continue;        book[i] = pnum;        prim[pnum++] = i;        for(int j = 2 ; j * i < 10000 ; j ++)            book[i*j]=1;    }    for(int i = 0 ; i < pnum ; i ++)    {        preC[i][1] = 1;        preA[i][1] = 1;        for(int j = 2 ; j < 10001 ; j ++)            preC[i][j] = preC[i][j-1] * inv(j,prim[i]) % prim[i];        for(int j = 2 ; j < 10001 ; j ++)            preA[i][j] = preA[i][j-1] * j % prim[i];    }}ll C(ll n,ll m,ll mod){    if(m>n) return 0;    if(m==n||m==0)return 1;    if(n==m+1||m==1)return n%mod;    return preA[book[mod]][n]*preC[book[mod]][m]%mod*preC[book[mod]][n-m]%mod;}ll lucas(ll n,ll m,ll mod){    if(m == 0) return 1;    return C(n%mod,m%mod,mod)*lucas(n/mod,m/mod,mod)%mod;}int main(){    init();    int n,m,q,_case=0;    while(~scanf("%d%d%d",&n,&m,&q))    {        printf("Case #%d: %lld\n",++_case,2*m<n?(lucas(n+1,m,q)+n-m)%q:(lucas(n+1,m+1,q)+m)%q);    }    return 0;}











0 0
原创粉丝点击