[BZOJ3129][SDOI2013]方程

bzoj
luogu

description

有一个方程(x_1+x_2+...+x_n=M)
(n_1)个变量要求不得大于某个数,有(n_2)个变量要求不得小于某个数。
求方程的正整数解的数量模(10007)或者模(262203414)或者模(437367875)
(n_1,n_2le8,n_1+n_2le n,n,mle10^9)

sol

(n_2)个条件是没用的。
对前面(n_1)个条件容斥,然后就是把(m)个求放入(n)个盒子的方案数。
隔板法,组合数算一下,要用到(exLucas)

code

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
	int x=0,w=1;char ch=getchar();
	while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
	if (ch=='-') w=0,ch=getchar();
	while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
	return w?x:-x;
}
struct ex_Lucas{
	int p,pk,jc[20000];
	void init(){
		jc[0]=1;
		for (int i=1;i<=pk;++i)
			jc[i]=1ll*jc[i-1]*(i%p?i:1)%pk;
	}
	int fastpow(int a,int b){
		int res=1;
		while (b) {if (b&1) res=1ll*res*a%pk;a=1ll*a*a%pk;b>>=1;}
		return res;
	}
	void exgcd(int a,int b,int &x,int &y){
		if (!b) x=1,y=0;
		else exgcd(b,a%b,y,x),y-=a/b*x;
	}
	int inv(int a){
		int x,y;exgcd(a,pk,x,y);
		x=(x%pk+pk)%pk;return x;
	}
	int mul(int n){
		int res=1;
		while (n) res=1ll*res*fastpow(jc[pk],n/pk)%pk*jc[n%pk]%pk,n/=p;
		return res;
	}
	int C(int n,int m,int mod){
		int a=mul(n),b=mul(m),c=mul(n-m),k=0;
		for (int i=n;i;i/=p) k+=i/p;
		for (int i=m;i;i/=p) k-=i/p;
		for (int i=n-m;i;i/=p) k-=i/p;
		int ans=1ll*a*inv(b)%pk*inv(c)%pk*fastpow(p,k)%pk;
		return 1ll*ans*(mod/pk)%mod*inv(mod/pk)%mod;
	}
}a[6];
int tot;
int Lucas(int n,int m,int mod){
	if (n<0||m<0||n<m) return 0;int res=0;
	for (int i=1;i<=tot;++i) res=(res+a[i].C(n,m,mod))%mod;
	return res;
}
int main(){
	int Case=gi(),mod=gi(),x=mod;
	for (int i=2;i*i<=x;++i)
		if (x%i==0){
			a[++tot].p=i;a[tot].pk=1;
			while (x%i==0) a[tot].pk*=i,x/=i;
		}
	if (x>1) a[++tot].p=x,a[tot].pk=x;
	for (int i=1;i<=tot;++i) a[i].init();
	while (Case--){
		int n=gi(),n1=gi(),n2=gi(),m=gi()-n,w[10],ans=0;
		for (int i=0;i<n1;++i) w[i]=gi();
		for (int i=0;i<n2;++i) m-=gi()-1;
		for (int i=0;i<(1<<n1);++i){
			int tmp=m,bit=0;
			for (int j=0;j<n1;++j)
				if ((i>>j)&1) tmp-=w[j],++bit;
			if (bit&1) ans=(ans-Lucas(n+tmp-1,tmp,mod)+mod)%mod;
			else ans=(ans+Lucas(n+tmp-1,tmp,mod))%mod;
		}
		printf("%d
",ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/zhoushuyu/p/9469021.html