容斥定理

ACM训练联盟周赛

  •  131072K
 

Teemo decides to use his money to conquer the universe.

It is known that there are m planets that humans can reach at present. They are numbered from 1 to m. Teemo bought n kinds of gateways. Their IDs are a1, a2, ..., an, the gateway whose ID is ai can transmit Teemo to the stars numbered ai,2ai, 3ai, ..., k*ai (1<=k*ai<=m, k is a positive integer), now Teemo wants to know, how many planets can he reach?

 

Input Format

On the firstline one positive number: the number of test cases, at most 20. After that per test case:

  • One line contains two integers n and m, (1 <= n <= 15, 1<= m < = 1e9), respectively represent the number of the gateway, the number of the stars that humans can reach.
  • One line contains integers, the i-th integer a[i], indicating that the ID of the  i-th gateway is a[i], (2<=a[i]<=1e9).

 

Ouput Format

Per test case:

  • One line contains an integer, which indicates how many planets Teemo can reach at most.

 

样例输入

2
2 15
2 3
5 100
2 3 4 5 6

样例输出

10
74

复制代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <string>
#include <deque>
#include <map>
#include <vector>
#include <stack>
using namespace std;
#define  ll long long 
#define  N   29
#define  M 1000000000
#define  gep(i,a,b)  for(int  i=a;i<=b;i++)
#define  gepp(i,a,b) for(int  i=a;i>=b;i--)
#define  gep1(i,a,b)  for(ll i=a;i<=b;i++)
#define  gepp1(i,a,b) for(ll i=a;i>=b;i--)    
#define  mem(a,b)  memset(a,b,sizeof(a))
#define  ph  push_back
/*
int、long long类型都可以,需要注意的是两个类型必须要相同
还有就是不能用浮点型,当然也可以手写gcd函数,它头文件是algorithm。
*/
ll lcm(ll a,ll b){ ll c=__gcd(a,b); return a/c*b; } int t; ll n,m,a[N]; //C(n,1)+C(n,2)+C(n,3)+……+C(n,n)==(2^n)-1 int main() { scanf("%d",&t); while(t--){ scanf("%lld%lld",&n,&m); ll sum=0; gep(i,0,n-1) scanf("%lld",&a[i]); gep(i,1,(1<<n)-1){//最大(1<<n)-1,C(n,n) ll cnt=0,ans=1; gep(j,0,n-1){//j从0开始 if(i&(1<<j)){ cnt++;//C(n,cnt) ans=lcm(ans,a[j]); if(ans>m) break; } } sum+=cnt%2?m/ans:-m/ans;//容斥定理+1-2+3-4…… } printf("%lld\n",sum); } return 0; }
复制代码

 

 

如果被计数的事物有A、B、C三类,那么,A类和B类和C类元素个数总和= A类元素个数+ B类元素个数+C类元素个数—既是A类又是B类的元素个数—既是A类又是C类的元素个数—既是B类又是C类的元素个数+既是A类又是B类而且是C类的元素个数。
(A∪B∪C = A+B+C - A∩B - B∩C - C∩A + A∩B∩C)

 

posted on   cltt  阅读(259)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示