HDU3944 DP? (LUCAS定理+阶乘预处理)

此博客讨论了如何计算杨辉三角中从顶部到指定行和列的最小路径和,考虑了路径方向限制,并提供了求解算法及实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 2 4 2 7
 

Sample Output
Case #1: 0 Case #2: 5
题目分析:要求计算最小的和,
当 k < n/2 时需要将C(N,K) 化成 C(N,N-K);
原式 C(N,K)+C(N-1,K-1)+...+C(N-K,0)+K;
由 C(N-1,K)+C(N-1,K-1)=C(N,K) 原式可化为C(N+1,K)+K;
然后经过Lucas定理+对阶乘的预处理即可得出结果;
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int N = 10005;

bool prime[N];

int p[N],f[N][N],inv[N][N],cnt,pth[N];

void isprime(){
    cnt=0;
    memset(prime,1,sizeof(prime));
    for(int i=2;i<N;i++){
        if(prime[i]){
            p[++cnt]=i;
            pth[i]=cnt;
            for(int j=i+i;j<N;j+=i)
                prime[j]=0;
        }
    }
}

int quick_mod(int a,int b,int m){
    int ans=1;
    a%=m;
    while(b){
        if(b&1){
            ans=ans*a%m;
            b--;
        }
        b>>=1;
        a=a*a%m;
    }
    return ans;
}

void init(){//预处理阶乘与逆元
    int i,j;
    for(int i=1;i<=cnt;i++){
        f[i][0]=inv[i][0]=1;
        for(int j=1;j<p[i];j++){
            f[i][j]=(f[i][j-1]*j)%p[i];
            inv[i][j]=quick_mod(f[i][j],p[i]-2,p[i]);
        }
    }
}

int com(int n,int m,int P){
    if(m>n) return 0;
    if(m==n) return 1;
    int t=pth[P];
    return f[t][n]*(inv[t][n-m]*inv[t][m]%P)%P;
}

int lucas(int n,int m,int P){
    if(m==0) return 1;
    return com(n%P,m%P,P)*lucas(n/P,m/P,P)%P;
}
int main()
{
    int cas=1,n,m,P;
    isprime();
    init();
    while(cin>>n>>m>>P){
        if(m<=n/2) m=n-m;
        n++;
        printf("Case #%d: %d\n",cas++,(m%P+lucas(n,m+1,P))%P);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值