题意:给一个集合,一共n个元素,从中选取m个元素,选出的元素中没有相邻的元素的选法一共有多少种?
插板法的经典应用
0.首先我们拿出m个小球,还剩下n-m个小球。这n-m个小球一共有n-m+1个空(左右两边也可以),把这m个小球插入到这n-m+1个空里就是答案,即
这m个小球的编号取决于它插入的位置,所以和选哪个小球没关系.
1.1<= p <=1e9不能预处理
#include <iostream>//Lucas模板
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#define IO ios::sync_with_stdio(false),cin.tie(0), cout.tie(0);
#pragma comment(linker, "/STACK:1024000000,1024000000")
void ex_gcd(int a, int b, int &d, int &x, int &y) { if (!b) { x = 1; y = 0; d = a; } else { ex_gcd(b, a%b, d, y, x); y -= x * (a / b); }; }
int gcd(int a, int b) { return b ? gcd(b, a%b) : a; }
int lcm(int a,int b){return a/gcd(a,b)*b;}//Ïȳýºó³Ë·ÀÒç³ö
int inv_exgcd(int a, int m) { int d, x, y;ex_gcd(a, m, d, x, y);return d == 1 ? (x + m) % m : -1; }
typedef long long ll;
const int maxn=1e6;
using namespace std;
ll fac[maxn];
ll a,b,mod;
ll C(ll n,ll m,ll mod)
{
if(m>n)return 0;
ll ans=1;
for(int i=1;i<=m;++i)
{
ll a=(n+i-m)%mod,b=i%mod;
ans=ans*(a*inv_exgcd(b,mod)%mod)%mod;
}
return ans;
}
ll Lucas(ll n,ll m,ll mod)
{
if(m==0)return 1;
return C(n%mod,m%mod,mod)*Lucas(n/mod,m/mod,mod)%mod;
}
int main()
{
while(scanf("%lld%lld%lld",&a,&b,&mod)!=EOF)
{
a=a-b+1;
ll lu=Lucas(a,b,mod);
printf("%lld\n",lu);
}
return 0;
}