51Nod 1119 exgcd求逆元+组合数

传送门

题解:首先,M*N个方格,机器人每步只能向下或向右走,一共要走m+n-2步,而其中必须有m-1步向下,n-1步向右。也就是一个C什么什么的组合问题。

其次,题目数据要求取模,然而组合数中有除法,除法不可以直接取模,需要将除法转化为乘法,也就是乘以除法逆元。

求逆元常用的方法有费马小定理和扩展欧几里得法。费马小定理直接求a^(p-2)即可(p是mod的值)。而扩展欧几里得法就是将a,p代入方程,求出的x就是逆元。

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long LL;

const int INF = 0x3f3f3f3f;
const int MAXN = 50005;
const int mod = 1e9 + 7;

LL exgcd(LL a, LL b, LL &x, LL &y)
{
	if(a == 0 && b == 0)
	{
		return -1;
	}
	if(b == 0)
	{
		x = 1;
		y = 0;
		return 0;
	}
	LL d = exgcd(b, a%b, y, x);
	y -= a / b * x;
	return d;
}

//逆元
LL mod_reverse(LL a, LL n)
{
	LL x, y;
	LL d = exgcd(a, n, x, y);
	//if(d == 1)
		//return (x % n + n) % n;
	//else
		//return -1;
	return (x % n + n) % n;
}

LL C(LL m, LL n)
{
	LL i, t1, t2;
	t1 = t2 = 1;
	for(i = n; i >= n-m+1; --i)
	{
		t1 = t1 * i % mod;
	}
	for(i=1; i <= m; ++i)
	{
		t2 = t2 * i % mod;
	}
	return t1 * mod_reverse(t2, mod) % mod;
}

int main() {
	LL m, n;
	cin >> m >> n;
	cout << C( min(m-1, n-1), m+n-2);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值