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

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

相关推荐
mmmmath_31 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z1 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧2 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背3 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝3 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD3 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl5 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
木子算法5 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪
虚无的纽扣5 小时前
【力扣刷题】第二天:无重复字符的最长字串、移动零问题
算法·leetcode·排序算法