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.
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,
x1、y1、x2、y2、p.x1≤x2≤105,y1≤y2≤105,2≤p≤109
.
You should calculate ∑x2i=x1∑y2j=y1ai,j mod p
You should calculate ∑x2i=x1∑y2j=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;
}