标签:int LL 容斥 cin long dfs ans 原理
https://www.acwing.com/problem/content/description/892/
给定一个整数 \(n\) 和 \(m\) 个不同的质数 \(p_1, p_2, ..., p_m\)。
请你求出 1 ∼ \(n\) 中能被 \(p_1, p_2, ..., p_m\) 中的至少一个数整除的整数有多少个。
二进制枚举所有可能。
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int main(){
ios::sync_with_stdio(false);cin.tie(0);
LL n, m;
cin >> n >> m;
vector <LL> p(m);
for (int i = 0; i < m; i ++ )
cin >> p[i];
LL ans = 0;
for (int i = 1; i < (1 << m); i ++ ){
LL t = 1, cnt = 0;
for (int j = 0; j < m; j ++ ){
if (i >> j & 1){
cnt ++ ;
t *= p[j];
if (t > n){
t = -1;
break;
}
}
}
if (t != -1){
if (cnt & 1) ans += n / t;
else ans -= n / t;
}
}
cout << ans << "\n";
return 0;
}
\(dfs\)
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int main(){
ios::sync_with_stdio(false);cin.tie(0);
LL n, m;
cin >> n >> m;
vector <LL> p(m);
for (int i = 0; i < m; i ++ )
cin >> p[i];
LL ans = 0;
function<void(LL, LL, LL)> dfs = [&](LL x, LL s, LL odd){
if (x == m){
if (s == 1) return;
ans += odd * (n / s);
return;
}
dfs(x + 1, s, odd);
if (s <= n / p[x]) dfs(x + 1, s * p[x], -odd);
};
dfs(0, 1, -1);
cout << ans << "\n";
return 0;
}
标签:int,LL,容斥,cin,long,dfs,ans,原理 来源: https://www.cnblogs.com/Hamine/p/16610405.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。