hdu 1796 How many integers can you find(容斥原理)

来源:互联网 发布:java解析xlsx文件 编辑:程序博客网 时间:2024/06/16 10:06

有坑,那就是可能输入0。这个容斥比较简单,枚举所有可能的情况,然后容斥,奇加偶减,共2^m种情况。计算lcm的时候小心int溢出

#include <bits/stdc++.h>using namespace std;int n,m;int mset[25];int lcm(int a, int b){    return a/__gcd(a,b)*b;}int main(){    int res;    ios::sync_with_stdio(false);    while(cin >> n >> m)    {        res = 0;        --n;        for(int i = 0; i < m; ++i)        {            cin >> mset[i];            if(mset[i] == 0)            {                --i;                --m;            }        }        for(int i = 1; i < (1<<m); ++i)        {            int mult = 1;            int num = 0;            for(int j = 0; j < m; ++j)            {                if(i&(1<<j))                {                    ++num;                    mult = lcm(mult,mset[j]);                }            }            if(num&1) res += n/mult;            else res -= n/mult;        }        cout << res << endl;    }    return 0;}