hdu-1796 How many integers can you find---容斥定理

本文介绍了一道编号为1796的HDU在线评测题目,该题目的核心在于计算1到n-1内能够被特定集合中任意一个数整除的数字个数。通过使用容斥原理并结合枚举子集的方法来求解,给出了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1796

题目大意:

给定n和一个大小为m的集合,集合元素为非负整数。为1...n-1内能被集合里任意一个数整除的数字个数。n<=2^31,m<=10

解题思路:

容斥定理

枚举m个元素的所有非空子集,求出lcm,如果子集元素数目为偶数那就减去,否则就加上。

挑战:P296有公式

 1 #include<iostream>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1e6 + 10;
 5 ll n, m;
 6 int a[50];
 7 ll gcd(ll a, ll b)
 8 {
 9     return b == 0 ? a : gcd(b, a % b);
10 }
11 void solve()
12 {
13     ll ans = 0;
14     for(int i = 1; i < (1 << m); i++)
15     {
16         int num = 0;
17         for(int j = i; j != 0; j >>= 1)if(j & 1)num++;//i的二进制中1的个数
18         ll lcm = 1;
19         for(int j = 0; j < m; j++)
20         {
21             if((1 << j) & i)
22             {
23                 lcm = lcm / gcd(lcm, a[j]) * a[j];
24                 if(lcm > n)break;
25             }
26         }
27         if(num&1)ans += n / lcm;
28         else ans -= n / lcm;
29     }
30     cout<<ans<<endl;
31 }
32 int main()
33 {
34     while(cin >> n >> m)
35     {
36         n--;//需要自减1,因为是1-n-1
37         int tot = 0, x;
38         for(int i = 0; i < m; i++)//可能有0元素
39         {
40             cin >> x;
41             if(x)a[tot++] = x;
42         }
43         m = tot;
44         solve();
45     }
46     return 0;
47 }

 

转载于:https://www.cnblogs.com/fzl194/p/9075139.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值