【容斥原理】1717 题解

本文探讨了组合数学中的并集求元素数量问题,并通过C++代码详细展示了如何运用递归与辗转相除法来解决该问题。文章提供了一个具体的实例,包括初始化输入、递归函数的设计以及最终结果的输出。

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

A=A1A2A3Am
|A|=mi=1|Ai|i<j|AiAj|+i<j<k|AiAjAk|++(1)m1|A1A2A3Am|

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cctype>
#include <cstring>
#include <algorithm>
#ifndef WIN32
#define Auto "%lld"
#else
#define Auto "%I64d"
#endif
using namespace std;
#define ll long long

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

int n, m;
int *arr;
ll res = 0;

inline void init() {
    int bn;
    scanf("%d%d", &bn, &m);
    arr = new int[(bn + 1)];
    for(int i = 1, x; i <= bn; i++) {
        scanf("%d", &x);
        if(x > 17)
            arr[++n] = x;
    }
}

void dfs(int dep, int flag, ll temp) {
    if(temp > m)    return;
    if(dep == n + 1) {
        if(temp > 1)
            res += flag * (m / temp);
        return;
    }
    int g = gcd(temp, arr[dep]);
    dfs(dep + 1, flag, temp);
    dfs(dep + 1, flag * -1, temp / g * arr[dep]);
}

inline void solve() {
    res = (m >= 17 && n) ? (1) : (0);
    m -= 17;
    dfs(1, -1, 1);
    printf(Auto, res);
}

int main() {
    init();
    solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值