码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ2836---Number Puzzle(容斥原理)

时间:2015-05-28 16:11:16      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:容斥原理

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

直接容斥

/*************************************************************************
    > File Name: zoj2836.cpp
    > Author: ALex
    > Mail: zchao1995@gmail.com 
    > Created Time: 2015年05月28日 星期四 15时50分38秒
 ************************************************************************/

#include <functional>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#include <set>
#include <vector>

using namespace std;

const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;

int A[20];

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

int main() {
    int n, m;
    while (~scanf("%d%d", &n, &m)) {
        for (int i = 0; i < n; ++i) {
            scanf("%d", &A[i]);
        }
        int ans = 0;
        for (int i = 1; i < (1 << n); ++i) {
            int numGcd = 1;
            int use = 0;
            for (int j = 0; j < n; ++j) {
                if (i & (1 << j)) {
                    ++use;
                    numGcd = numGcd / gcd(A[j], numGcd) * A[j];
                }
            }
            if (use & 1) {
                ans += m / numGcd;
            }
            else {
                ans -= m / numGcd;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

ZOJ2836---Number Puzzle(容斥原理)

标签:容斥原理

原文地址:http://blog.csdn.net/guard_mine/article/details/46124507

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!