上一篇博客主要详讲了容斥定理:点击打开链接
不过上一篇博客只是以3个集合为例来说明,并没有向无限推广;
今天这一篇博客就是xjb搞,从其他的博客中学来的;
1138 - 震惊,99%+的中国人都会算错的问题
Time Limit:4s Memory Limit:128MByte
Submissions:278Solved:78
DESCRIPTION
众所周知zhu是一个大厨,zhu一直有自己独特的咸鱼制作技巧.
tang是一个咸鱼供应商,他告诉zhu在他那里面有NN条咸鱼(标号从1到N)可以被用来制作.
每条咸鱼都有一个咸鱼值Ki,初始时所有Ki都是0.
zhu是一个特别的人,他有M个咸数(咸鱼数字), 对于每个咸数x,他都会让所有满足标号是xx倍数的咸鱼的咸鱼值异或上1.
zhu现在想知道经过了这M个咸数的筛选之后,最终有多少条的咸鱼的咸鱼值是1?
INPUT
输入的第一行包含一个整数
T(1≤T≤1000)
,表示有
T
组数据.对于每组数据:输入第一行只有两个整数
N(1≤N≤109)
,
M(1≤M≤15)
接下来一行有MM个整数,依次对应zhu的每个咸数(1≤咸数≤2∗105).
OUTPUT
对于每组数据,输出答案.
SAMPLE INPUT
2
10 1
3
10 1
1
SAMPLE OUTPUT
3
10
思路:这道题目就可以理解为关灯问题;总共有n个咸鱼值,m个询问;每次询问使得满足给出的咸鱼值的倍数的状态相反;通过上一篇博客知道三个集合的情况下为:n/a+n/b+n/c+2*(n/(a*b)+n/(a*c)+n/(b*c))+4*(n/(a*b*c));xjb搞一下,难道系数是每次增二倍?!
代码:
#include<bits/stdc++.h>
long long ans,a[30];
int n,m;
long long gcd(int a,int b)
{
return !b?a:gcd(b,a%b);
}
void dfs(int cur,long long lcm,int id)
{
lcm=lcm/gcd(lcm,a[cur])*a[cur];
if(id&1)
ans+=n/lcm*(1ll<<(id-1));
else
ans-=n/lcm*(1ll<<(id-1));
for(int i=cur+1;i<m;i++)
dfs(i,lcm,id+1);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
ans=0;
for(int i=0;i<m;i++)
scanf("%lld",&a[i]);
for(int i=0;i<m;i++)
dfs(i,a[i],1);
printf("%lld\n",ans);
}
return 0;
}
How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8088 Accepted Submission(s): 2411
Problem Description
Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0<N<2^31,0<M<=10, and the M integer are non-negative and won’t exceed 20.
Output
For each case, output the number.
Sample Input
12 2 2 3
Sample Output
7
思路:这道题目的意思是输入n、m,接下来输入m个数字;这m个数字,每个数的倍数小于n的总共有有多少个?这道题也可以理解为”开灯“问题,每次输入一个数字,打开这个数字的倍数且小于n的编号的灯泡;好啦就是这样!
代码:
#include<bits/stdc++.h>
long long ans,a[30];
int n,m;
long long gcd(int a,int b)
{
return !b?a:gcd(b,a%b);
}
void dfs(int cur,long long lcm,int id)
{
lcm=lcm/gcd(lcm,a[cur])*a[cur];
if(id&1)
ans+=(n-1)/lcm;
else
ans-=(n-1)/lcm;
for(int i=cur+1;i<m;i++)
dfs(i,lcm,id+1);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
ans=0;
int cnt=0;
for(int i=0;i<m;i++)
{
long long x;
scanf("%lld",&x);
if(x>0&&x<n) //坑点
a[cnt++]=x;
}
m=cnt;
for(int i=0;i<m;i++)
dfs(i,a[i],1);
printf("%lld\n",ans);
}
return 0;
}