HDU1796(容斥)

有几个坑点:

1.m个数中可能存在0

2.m个数的LCM可能爆int

3.比n小

3.如果m个数有1,直接输出n-1

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
#define maxn 11

long long n, num[maxn], m, cnt;

long long gcd (long long a, long long b) {
    return b == 0 ? a : gcd (b, a%b);
}

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

int count (int x, long long &mul) {
    mul = 1;
    int ans = 0;
    for (int i = 1; i <= m; i++, x >>= 1) {
        if (x&1) 
            ans++, mul = lcm (num[i], mul);
    }
    return ans;
}

int main () {
    while (cin >> n >> m) {
        bool ok = 0;
        cnt = 0;
        for (int i = 1; i <= m; i++) {
            cin >> num[++cnt];
            if (num[i] == 1)
                ok = 1;
            if (num[i] == 0)
                cnt--;
        }
        if (ok) {
            cout << n-1 << endl;
            continue;
        }
        m = cnt;
        long long ans = 0, mul; 
        for (int i = 1; i < (1<<m); i++) {
            int num_of_1 = count (i, mul);
            if (num_of_1&1)
                ans += (n-1)/mul;
            else ans -= (n-1)/mul;
        }
        cout << ans << endl;
    }
    return 0;
}


你可能感兴趣的:(HDU1796(容斥))