ZOJ 2836 - Number Puzzle(容斥原理)

Given a list of integers (A1, A2, …, An), and a positive integer M, please find the number of positive integers that are not greater than M and dividable by any integer from the given list.

Input
The input contains several test cases.

For each test case, there are two lines. The first line contains N (1 <= N <= 10) and M (1 <= M <= 200000000), and the second line contains A1, A2, …, An(1 <= Ai <= 10, for i = 1, 2, …, N).

Output
For each test case in the input, output the result in a single line.

Sample Input
3 2
2 3 7
3 6
2 3 7

Sample Output
1
4
题目链接
参考题解

题目大意就是给 n 个整数,和一个整数 m。求小于等于 m 的非负整数(1~ m )中能被这N个数中任意一个整除的数的个数。
答题思路就是利用容斥原理,如题解所说:设S1为1 ~ M中能被第一个整数A1整除的集合,S2为1~M中能被第二个整数A2整除的集合。
……
Sn为1~M中能被第N个整数An整除的集合。然后每个集合个数,其实就是M / An。
再根据容斥原理,求集合并集的元素个数即可。
其中要用到 lcm ,具体看代码就懂了。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
const int max_a = 10 + 5, maxn = 1e3 + 5;
ll factor[max_a], que[maxn];
ll n, m;

ll gcd(ll a, ll b)
{
    return !b ? a : gcd(b, a % b);
}

ll lcm(ll a, ll b)
{
    return a / gcd(a, b) * b;
}

ll solve()
{
    ll ans = 0;
    //这里枚举每一种情况,可以想象成一种小型的状压,每一个二进制位都是一个存在状态
    //也就是他给出的n个数,每一位代表一个数是否存在,存在为1,否则为0,
    //从1到1<<n也就枚举了所有可能出现的乘法组合
    for(int i = 1; i < (1 << n); ++i)
    {
        ll odd = 0, Lcm = 1;
        //如果当前乘法组合中有和这个数那么就进行lcm运算
        for(int j = 0; j < n; ++j)
        {
            if((1 << j) & i)
            {
                odd++;
                Lcm = lcm(Lcm, factor[j]);
            }
        }
        //容斥原理,奇数加偶数减
        if(odd & 1)
            ans += m / Lcm;
        else
            ans -= m / Lcm;
    }
    return ans;
}

int main()
{
    while(~scanf("%lld%lld", &n, &m))
    {
        for(int i = 0; i < n; i++)
            scanf("%lld", &factor[i]);
        ll ans = solve();
        printf("%lld\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/83575931