传送门在这里
题意:求Sum(C[i][j]) (x1<=i<=x2;y1<=j<=y2),结果对质数p取模
思路:由c[i][j]=c[i-1][j-1]+c[i-1][j]可知Sum(C[i][k]) = C[b+1][k+1]-C[a][k+1] (a<=i<=b),所以枚举所有的j算出C[x2+1][j+1]-C[x1][j+1]即可。计算c[n][m]对p取模的值需要用到Lucas定理。
Lucas定理:C[n][m]%p=C[n/p][m/p]*C]n%p][m%p]%p
令a=n%p,b=m%p,
则C[a][b]=a!/(b!*(a-b)!)
由于b!*(a-b)!与p互质,由费马小定理,C[a][b]=a!*(b!*(a-b)!)^(p-2)
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define LL long long
LL PowMod(LL a,LL b,LL MOD){
LL ret=1;
while(b){
if(b&1) ret=(ret*a)%MOD;
a=(a*a)%MOD;
b>>=1;
}
return ret;
}
LL fac[100005];
LL GetFact(LL p){
fac[0]=1;
for(LL i=1;i<=100000;i++){
fac[i]=fac[i-1]*i%p;
}
}
LL Lucas(LL n,LL m,LL p){
if(n<m) return 0;
LL ret=1;
while(n&&m){
LL a=n%p,b=m%p;
if(a<b) return 0;
ret=(ret*fac[a]*PowMod(fac[b]*fac[a-b]%p,p-2,p))%p;
n/=p;m/=p;
}
return ret;
}
int main(){
int x1,x2,y1,y2,p;
while(scanf("%d%d%d%d%d",&x1,&y1,&x2,&y2,&p)!=EOF){
GetFact(p);
LL ans=0;
for(int i=y1+1;i<=y2+1;i++){
ans=(ans+Lucas(x2+1,i,p)-Lucas(x1,i,p)+p)%p;
}
cout<<ans<<endl;
}
return 0;
}