题目大意:有一个大小为 n 的正整数集合,一个好的数的定义为它至少是集合中的一个数的倍数,找出 1 至 m(包括 m)中好的数的个数
输入:第一行两个整数,n 和 m;第二行是 n 个正整数,表示这个集合。
输出:一行答案。
数据规模与约定:设 ai 为集合中的数,对于 100%的数据,1≤n≤16,m≤1015,1≤ai≤103
MyCode
// 思路:容斥,O(2 ^ n),枚举一个子集S,ans += -1 ^ |S| - 1 * m / lcm (S)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll n, m, a[20], c[20], ans;
bool b[20];
ll gcd (ll x, ll y)
{
if (x % y == 0) return y;
return gcd (y, x % y);
}
ll lcm (int x)
{
long long res = 1;
for (int i = 1; i <= x; i++)
res = res / gcd (a[c[i]], res) * a[c[i]];
return res;
}
int dfs (int k, int r)
{
for (int i = 1; i <= n; i++)
if (!b[i] && c[k - 1] < i)
{
c[k] = i; b[i] = 1;
if (k == r)
ans += pow (-1, r - 1) * (m / lcm (r));
else dfs (k + 1, r);
b[i] = 0;
}
}
int main ( )
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++)
{
dfs (1, i);
memset (b, 0, sizeof (b));
}
cout << ans << '\n';
return 0;
}
但是,运行错误!求调
一周站外题求助了 N 次的蒟蒻