Acwing.886 求组合数Ⅱ

题目

给定n组询问,每组询问给定两个整数a, b,请你输出

的值。

输入格式

第一行包含整数n。

接下来n行,每行包含---组a和b。

输出格式

共n行,每行输出---个询问的解。

数据范围

1<n≤10000,

1 <b<a≤105

  • 输入样例:
cpp 复制代码
3
3 1
5 3
2 2
  • 输出样例:
cpp 复制代码
3
10
1

题解

cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;
const int N = 100010,mod = 1e9 + 7;

int fact[N], infact[N];

int qmi(int a, int k, int p)
{
	int res = 1;
	while (k)
	{
		if (k & 1) res = (LL)res * a % p;
		a = (LL)a * a % p;
		k >>= 1;
	}	
	return res;
}	
int main()
{
	fact[0] = infact[0]= 1;
	for ( int i = 1; i <N; i ++ )
	{
		fact[i] = (LL)fact[i - 1]* i % mod;
		infact[i] = (LL)infact[i - 1] * qmi(i,mod - 2, mod) % mod;
	}
I
	int n;
	scanf("%d"", &n);
	while (n -- )
	{
		int a, b;
		scanf(""%d%d"",&a,&b);
		printf("%d\n",(LL)fact[a] * infact[b] % mod * infact[a - b] % mod) ;
	}	
	return 0;
}	

思路

组合数1用的思想是递推,但是在数据量大的时候超时,我们需要进行预处理,根据下图数学知识

我们提前算出阶乘数组,最后带入公式求得答案。

相关推荐
tryxr20 分钟前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_324 分钟前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia34 分钟前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z1 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.1 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark1 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd2 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
晴天的雨.9925 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae11 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法