题目链接
容斥模板
题目描述,N, M , 然后输入M个数,求1 到N-1内 能被M中的数整除的个数
思路:M个数中进行组合,如果为奇数个则+,为偶数个则 -。用Dfs 找组合数。
#include<iostream>
#include<cstring>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int Maxn = 20;
int Number[Maxn + 5];
int N, M, Tot;
LL Ans = 0;
LL Gcd(LL A, LL B){
return !B ? A : Gcd(B, A % B);
}
void Dfs(int Cur, int Cnt, int Limit, LL LCM){
if (Cnt == Limit) {
if (Limit & 1) {
Ans += (N - 1) / LCM;
}
else {
Ans -= (N - 1) / LCM;
}
return;
}
if (Cur >= Tot) {
return ;
}
LL NowLCM = LCM == -1 ? Number[Cur] : LCM;
Dfs(Cur + 1, Cnt + 1, Limit, Number[Cur] / Gcd(NowLCM, Number[Cur]) * NowLCM);
Dfs(Cur + 1, Cnt, Limit, LCM);
}
int main(){
while (~scanf("%d%d", &N, &M)) {
Tot = 1;
int X;
for (int i = 1; i <= M; ++i) {
scanf("%d", &X);
if (X) {
Number[Tot++] = X;
}
}
Ans = 0;
for (int i = 1; i < Tot; i++) {
Dfs(1, 0, i, -1);
}
printf("%lld\n", Ans);
}
}
应该是有更快的方法
思路:上述方法是找出一组(比如找出3个)的后(把3个的不同组合全找出来再进行+-)但是我们找(4······N-1)时发现3个不同的组合是 (4·····N-1)的子集,那就可以在找的过程中进行+-。