算法基础之组合数 II

算法基础之组合数 II

  • 核心思想:快速幂求逆元

    • 前置:Cba = a! /(b! * (a-b)!)
      • 即 faca * infacb * infaca-b;
cpp 复制代码
  #include <iostream>
  #include <cstring>
  #include <algorithm>
  
  using namespace std;
  const int MOD = 1e9+7,N = 1e5+10;
  typedef long long LL;
  
  long long fac[N],infac[N];
  int n;
  
  int qmi(int a,int b,int k)  //快速幂求逆元
  {
      int res = 1;
      while(b)
      {
          if(b&1) res = (LL)res*a%k;
          b>>=1;
          a = (LL)a*a%k;
      }
      return res;
  }
  int main()
  {
      fac[0] = infac[0] = 1;
      for(int i=1;i<=100000;i++)  //预处理
      {
          fac[i] = fac[i-1] * i % MOD;
          infac[i] = (LL)infac[i-1] * qmi(i,MOD-2,MOD)%MOD;
      }
      cin>>n;
      while(n--)
      {
          int a,b;
          cin>>a>>b;
          //多%几次 会爆
          cout<<(LL)fac[a] * infac[b]%MOD * infac[a-b] %MOD<<endl;
      }
  }
相关推荐
千里码aicood3 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅3 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊3 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له4 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿4 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
2601_962218615 小时前
C++中decltype关键字的实现
开发语言·c++
Discipline10296 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
繁华的地方不一定留下你的脚印6 小时前
C++ std::variant 与 std::visit:安全保存多种类型,写清每个处理分支
开发语言·c++
XuCoder6 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法