Tom and matrix
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 447 Accepted Submission(s): 136
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,i)+C(i+1,i).....+C(n,i)=C(n+1,i+1)。
然后枚举i=1到m即可。
然后按容斥分成四个矩形即可。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
#define maxn 100007
#define ll long long
ll jie[maxn];
ll ni[maxn];
ll cal(ll n,ll t,ll p){
ll ans = 1;
while(t){
if(t&1) ans = (ll)ans*n%p;
n = (ll)n*n%p;
t/=2;
}
return ans;
}
void init(ll p){
jie[0] = ni[0] = 1;
for(ll i = 1;i < maxn;i++){
jie[i] = jie[i-1]*i%p;
ni[i] = cal(jie[i],p-2,p);
}
}
ll Lucas(ll n,ll m,ll p){
if(m == 0 ) return 1;
ll a = n % p, b = m % p;
if(a < b) return 0;
ll ans = 0;
ans = jie[a]*ni[a-b]%p*ni[b]%p;
return (ll)Lucas(n/p,m/p,p)*ans%p;
}
ll work(ll n,ll m,ll p){
ll ans = 0;
for(ll i = 1;i <= min(n,m)+1; i++){
ans += Lucas(n+1,i,p);
ans %= p;
}
return ans;
}
int main(){
ll x1,x2,y1,y2,p;
while(cin>>x1>>y1>>x2>>y2>>p){
init(p);
ll ans = 0;
ans += work(x2,y2,p);
if(x1) ans -= work(x1-1,y2,p);
ans %= p;
if(y1) ans -= work(x2,y1-1,p);
ans %= p;
if(x1 && y2) ans+=work(x1-1,y1-1,p);
ans = (ans%p+p)%p;
cout<<ans<<endl;
}
return 0;
}