Lucas定理+乘法逆元+组合数学(hdu5226)

Tom and matrix

Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 189    Accepted Submission(s): 57


Problem Description
Tom was on the way home from school. He saw a matrix in the sky. He found that if we numbered rows and columns of the matrix from 0, then,
ai,j=Cji

if i < j, ai,j=0

Tom suddenly had an idea. He wanted to know the sum of the numbers in some rectangles. Tom needed to go home quickly, so he wouldn't solve this problem by himself. Now he wants you to help him.
Because the number may be very large, output the answer to the problem modulo a prime p.
 

Input
Multi test cases(about 8). Each case occupies only one line, contains five integers, x1y1x2y2p.x1x2105,y1y2105,2p109 .

You should calculate x2i=x1y2j=y1ai,j mod p
 

Output
For each case, print one line, the answer to the problem modulo p.
 

Sample Input
  
  
0 0 1 1 7 1 1 2 2 13 1 0 2 1 2
 

Sample Output
  
  
3 4 1
 

Source
 
思路:因为
∑C(i,k)(a<=i<=b)=C(b+1,k+1)-C(a,k+1),所以求同一列的数的和可以变成求两个组合数的差。因为要模p,p还可能很小,所以可以用lucas定理:C(m,n)≡C(m/p.n/p)⋅C(m%p,n%p)(mod p)。可以预处理阶乘。设n=max(x1,y1,x2,y2),那么时间复杂度:O(n⋅logn)

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=100010;
LL f[maxn];
int N,M,p;
int x1,x2,y11,y2;
void init()
{
    f[0]=1;
    for(int i=1;i<=min(x2+1,p-1);i++)
        f[i]=f[i-1]*i%p;
}
LL pow_mul(LL a,LL b)
{
    LL res=1;
    while(b)
    {
        if(b&1)res=res*a%p;
        a=a*a%p;
        b>>=1;
    }
    return res;
}
LL C(LL n,LL m)
{
    if(m>n)return 0;
    return f[n]*pow_mul(f[m]*f[n-m]%p,p-2)%p;
}
LL Lucas(LL n,LL m)
{
    if(m==0)return 1;
    else return (C(n%p,m%p)*Lucas(n/p,m/p))%p;
}

int main()
{
    while(scanf("%d%d%d%d%d",&x1,&y11,&x2,&y2,&p)!=EOF)
    {
        LL ans=0;
        init();
        for(int i=y11;i<=y2;i++)
        {
            ans+=(Lucas(x2+1,i+1)-Lucas(x1,i+1)+p)%p;
        }
        cout<<ans%p<<endl;
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值