UVA 10325 The Lottery 容斥原理

UVA 10325 The Lottery 容斥原理

链接:UVA 10325 The Lottery
在这里插入图片描述
题意:给你两个正整数 n , m n,m ,然后给你 m m 个正整数 a 1 , a 2 , , a m a_1,a_2,···,a_m ,让你找出 1 1 ~ n n 中有多少个数不是这 m m 个数的倍数?
题解:显然,我们会想到用 n n 减去 n / a i n/a_i ,但是这样会有一些元素会重复计算,我们就需要用容斥原理把重复计算的数减掉,像第一个样例: 3 = 10 10 / 2 10 / 3 + 10 / ( 2 3 ) 3 =10-10/2-10/3+10/(2*3) ,但是对于对于第二个样例: 10 ! = 20 20 / 2 20 / 4 + 20 / ( 2 4 ) = 7 10!=20-20/2-20/4+20/(2*4) =7 ,这时我们就要想什么样的数应该进行容斥,对于第二个样例来说, 2 2 的倍数应该被减去, 4 4 的倍数也被减去,那么什么样的数应该加进来呢?我们发现 4 , 8 , 12 , 16 , 20 4,8,12,16,20 被减过两次, 2 , 6 , 10 , 14 , 18 2,6,10,14,18 被减过一次,那么我们发现应该将 4 4 的加进来,即 10 = 20 20 / 2 20 / 4 + 20 / 4 10 = 20-20/2-20/4+20/4 ,我们发现 4 = l c m ( 4 , 2 ) 4 = lcm(4,2) ,到此我们就可以得出结果: a n s = n 1 m n / a i + 1 i < j m n / l c m ( a i , a j ) + ( 1 ) m n / l c m ( a 1 , a 2 , , a m ) ans =n-\sum_1^m {n/a_i}+\sum \limits_{1 \le i< j \le m}{n/lcm(a_i,a_j)}-···+(-1)^m*n/lcm(a_1,a_2,···,a_m) .可以求出最终结果。
代码:

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
const int maxn = 1e5+100;
int a[maxn];
int num[maxn];

LL gcd(LL a, LL b)
{
    if(b==0)
        return a;
    return gcd(b, a%b);
}

int main()
{
    int n,m;
    while(~scanf("%d%d", &n, &m))
    {
        int a[20];
        for(int i = 1; i <= m;i++)
        {
            scanf("%d", &a[i]);
        }
        LL ans = 0;
        //容斥枚举全部子集模板
        for(int i = 0; i <(1<<m);i++)//1----
        {
            int cnt = 0;
            LL d = 1;
            for(int j = 1;j<=m;j++)//2----
            {
                if((i>>(j-1))&1)//3----
                {
                    cnt++;
                    d = a[j]/gcd(a[j],d)*d;
                }
            }
            if(cnt&1)
            {
                ans -= n/d;
            }
            else
            {
                ans += n/d;
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}
//模板形式
{
	for(int i = 0; i <(1<<m);i++)//1----
        for(int j = 1;j<=m;j++)//2----
           	if((i>>(j-1))&1)//3----
}
发布了27 篇原创文章 · 获赞 13 · 访问量 1702

猜你喜欢

转载自blog.csdn.net/weixin_43855330/article/details/103229429