ZOJ 3557 - How Many Sets II(Lucas定理模板)

题目链接 https://cn.vjudge.net/problem/ZOJ-3557

【题意】
从n个相同小球中取m个小球,不能取相邻的小球的方案数

【思路】
首先拿出 mm 个小球,还剩下 nmn-m 个小球。这 nmn-m 个小球一共有 nm+1n-m+1 个空(左右两边也可以),把这 mm 个小球插入到这 nm+1n-m+1 个空里就是答案,即Ans=Cnm+1mAns=C_{n-m+1}^{m},记录一下LucasLucas 定理的模板

Lucas 定理

求解 Cnm  (modp)C_n^m \ \ (mod p)
首先将n和m分解为p进制:
n=nkpk+nk1pk1+...+n1p+n0n=n_kp^k+n_{k-1}p^{k-1}+...+n_1p+n_0 m=mkpk+mk1pk1+...+m1p+m0m=m_kp^k+m_{k-1}p^{k-1}+...+m_1p+m_0 那么 Ansi=0kCnimi  (modp)Ans≡∏_{i=0}^{k}C_{n_i}^{m_i} \ \ (modp)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn=10050;
int mod;

ll pw(ll x,ll n){
	ll ans=1LL;
	while(n){
		if(n&1) ans=ans*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return ans;
}

ll inv(ll a){return pw(a,mod-2);}

ll C(int n,int m){
    if(m>n) return 0LL;
    ll up=1LL,down=1LL;
    for(int i=n-m+1;i<=n;++i) up=up*i%mod;
    for(int i=1;i<=m;++i) down=down*i%mod;
    return up*inv(down)%mod;
}

ll Lucas(int n,int m){
	if(m>n) return 0LL;
    ll ans=1LL;
    for (;m;n/=mod,m/=mod)
        ans=ans*C(n%mod,m%mod)%mod;
    return ans;
}

int main(){
	int n,m;
	while(scanf("%d%d%d",&n,&m,&mod)==3){
		printf("%lld\n",Lucas(n-m+1,m));
	}
	return 0;
}
posted @ 2018-10-18 19:34  不想吃WA的咸鱼  阅读(225)  评论(0编辑  收藏  举报