nefu 628 Garden visiting(非降路径模板题)

24 篇文章 0 订阅

Garden visiting

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

							

hint

Sample 1: There are 2 routes in total. 
Sample 2: There are 6 routes in total.
Sample 3: There are 252 routes in total.

题意:给你一个长为m,宽为n的矩形,求从左上角到右下角经过最少步数的走法有多少种。

            就是我们常说的非降路径数。从(a,b)到(m,n)共有C(m+n-a-b,m-a)种.

代码:

#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long  ll;
const int Max=200005;

int prime[Max],num,p[Max];
int cal(int n,int k)
{
    int res=0;
    while(n>=k)
    {
        n/=k;
        res+=n;
    }
   return res;
}
int pp(ll x,ll k,int mod)//快速幂取模
{
   ll ans=1;
   while(k>0)
   {
      if(k&1)ans=(ans*x)%mod;
      x=(x*x)%mod;
      k>>=1;
   }
   return ans;
}
void init()//素数判定
{
    for(int i=2;i<Max;i++)
     if(!p[i])
      {
        prime[num++]=i;
        for(int j=i+i;j<Max;j+=i)
            p[j]=1;
    }
}
void work()
{
     int n,m,mod;
     scanf("%d%d%d",&n,&m,&mod);
     n+=m-2;
     m--;
     ll ans=1;
    for(int i=0;i<num&&prime[i]<=n;i++)
    {
        int p=cal(n,prime[i])-cal(m,prime[i])-cal(n-m,prime[i]);
        ans=ans*pp(prime[i],p,mod)%mod;
    }
    printf("%d\n",(int)ans);
}
int main()
 {
  int t;
   init();
 cin>>t;
 while(t--)
   {
       work();
   }
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值