跳到正文

题解

abc423f || Loud Cicada

AnllAn约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

早知道先开 F 了,个人差来说 F<<E。

思路

发现 n≤20n\le 20,直接无脑容斥。具体地,我们枚举 nn 个数所有的可能组合方式。记当前方案出现的数总数为 tottot,如果 tot<mtot<m 肯定不作任何贡献,否则经典容斥即可:若 (tot−m) mod 2=0(tot-m) \bmod 2=0 则加,否则减。贡献为 an×Ctotman\times C_{tot}^{m},其中 anan 表示这些数一起出现的总位置数,组合数的意义为在 tottot 里选 mm 个的方案数。至于计算总位置数,直我们考虑到每次出现都一定是某个数 kk 的倍数,显然 kk 是选中的数的小公倍。

具体实现时会出一些问题。首先因为怕爆 long long 所以计算时用的 __int128。因此输出时需要特判 ans=0ans=0 的情况。其次,如果每次暴力去计算 kk 会直接 TT 飞,因为 gcd⁡\gcd 的时间复杂度是 log⁡\log 的。因此我们可以把每个集合对应的 kk 存下来,这样下次更新的时候只需要再计算一次 gcd⁡\gcd 即可。以及组合数也可以提前预处理出来。

代码

写的有点丑。

C++
#include<iostream>
#define int long long
using namespace std;
int n,m;
__int128 Y,ans,A[30],C[30][30],G[2000005];
string s;
void print(__int128 a){
	string ss;
	while(a){
		ss+=(char)('0'+a%10);
		a/=10;
	}
	for(int i=ss.size()-1;i>=0;i--) cout<<ss[i];
}
__int128 gcd(__int128 a,__int128 b){
	if(a%b==0) return b;
	return gcd(b,a%b);
}
__int128 C_(int a,int b){
	__int128 an=1;
	for(int i=a+1;i<=b;i++){
		an*=i;
	}
	for(int i=1;i<=b-a;i++){
		an/=i;
	}
	return an;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n>>m>>s;G[0]=1;
	for(int i=0;i<=n;i++)
		for(int j=i;j<=n;j++)
			C[i][j]=C_(i,j);
	for(int j=0;j<s.size();j++)
		Y=Y*10+(s[j]-'0');
	for(int i=1;i<=n;i++){
		cin>>s;
		for(int j=0;j<s.size();j++)
			A[i]=A[i]*10+(s[j]-'0');
	}
	for(int i=1;i<(1<<n);i++){
		int tot=0;__int128 an=1;
		for(int j=1;j<=n;j++){
			if(i>>j-1&1){
				tot++;
				if(tot==1){
					__int128 g=gcd(A[j],G[i-(1<<j-1)]);
					if(G[i-(1<<j-1)]>Y){
						an=G[i]=Y+1;
						break;
					}
					an=A[j]/g*G[i-(1<<j-1)];
					G[i]=an;
					if(G[i]>Y){
						an=G[i]=Y+1;
						break;
					}
				}
			}
		}
		if(tot<m||an>Y) continue;
		int c=tot-m;
		ans=(ans+(c%2==0?1:-1)*(Y/an)*C[c][tot]);
	}
	if(!ans) cout<<0;
	else print(ans);
	return 0;
}
原文