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用的思想是递推,但是在数据量大的时候超时,我们需要进行预处理,根据下图数学知识

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

相关推荐
非优秀程序员7 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
武子康14 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw0520 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术20 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs21 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057591 天前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI1 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵