继上一次继续讲,问题来源于: http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=628
大意是n*m的方格,从左上方走到右下方,以最少的步数有多少走法。数据级1e5,动态规划思路肯定不行。注意到总步数是n+m-2,一条水平的路线对应唯一一条垂直路线,以时间为思考基础,什么时候水平走,什么时候竖直走,所以结果就应该是C(n+m-2,m-1) 或者 C(n+m-2,n-1)。所以问题转化成:求C(n,m) mod p [1<=m,p<=100000,0<=n<200000]
p不是素数就不能用n^(p-2)的形式求解逆元,注意到数据级是1e5,那么素因子分解后大概是350,故暴力分解再快速幂取模是个可行的方案。
原问题:
Garden visiting |
Problem : 628 |
Time Limit : 1000ms |
Memory Limit : 65536K |
|
description |
There is a very big garden at Raven’s residence. We regard the garden as an n*m rectangle. Raven’s house is at the top left corner, and the exit of the garden is at the bottom right. He can choose to take one step to only one direction (up, down, left or right) each time. Raven wants to go out of the garden as quickly as possible, so he wonders how many routes he could choose.
Raven knows there are many possible routes, so he only wants to know the number, which is the result that the total number of possible routes modes a given value p. He knows it is a simple question, so he hopes you may help him to solve it.
|
input |
The first line of the input contains an integer T, which indicates the number of test cases.
Then it is followed by three positive integers n, m and p (1 <= n, m, p <= 10^5), showing the length and width of the garden and p to be the mod of the result.
|
output |
For each case, output one number to show the result (the sum modes p). |
sample_input |
3
2 2 5
2 6 16
6 6 24
|
sample_output |
2
6
12
|
#include <iostream>
#include <cstdio>
using namespace std;
const int N=2e5+5;
typedef long long LL;
LL fac[N/10],cnt=0;
bool notprime[N];
void getprime(){
for(LL i=2;i<N;i++){
if(!notprime[i]) fac[cnt++]=i;
for(LL j=0;j<cnt&&fac[j]*i<N;j++){
notprime[fac[j]*i]=1;
if(i%fac[j]==0) break;
}
}
}
LL power(LL a,LL b,LL m){
LL ans=1,t=a%m;
while(b){
if(b&1) ans=ans*t%m;
t=t*t%m;
b>>=1;
}
return ans;
}
LL get(LL x,LL p){
LL ans=0;
while(x){
ans=ans+x/p;
x/=p;
}
return ans;
}
LL work(LL n,LL m,LL p){
LL ans=1;
for(LL i=0;i<cnt&&fac[i]<=n;i++){ //fac[i]<=n
//计算阶乘含有的素因子的个数。
LL t1=get(n,fac[i]),t2=get(n-m,fac[i]),t3=get(m,fac[i]);
ans=ans*power(fac[i],t1-t2-t3,p)%p; //0!= 1 power有保证
}
return ans;
}
int main()
{
//freopen("cin.txt","r",stdin);
getprime();
LL t;
cin>>t;
while(t--){
LL n,m,p;
scanf("%lld%lld%lld",&n,&m,&p);
n=n+m-2;
m--;
printf("%lld\n",work(n,m,p));
}
return 0;
}