zoj 2836 Number Puzzle(容斥原理)

来源:互联网 发布:云和山的彼端 mac 编辑:程序博客网 时间:2024/05/22 10:57

题目链接:传送门

Number Puzzle
Time Limit: 2 Seconds Memory Limit: 65536 KB
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

题意:有n个数,问m中有多少个数(这个数是,能被n个数中任意一个数整除)。

思路:容斥原理,最简单的,适合新手。

#include<stdio.h>#include<string.h>int n,m,a[15];int sum;int gcd(int x,int y){    if(y)        return gcd(y,x%y);    return x;}int lcm(int x,int y){    return x*y/gcd(x,y);}void dfs(int x,int k,int f){    sum+=k*m/f;    for(int i=x;i<n;i++)    {        dfs(i+1,-k,lcm(a[i],f));    }}int main(){    while(~scanf("%d%d",&n,&m))    {        for(int i=0;i<n;i++)            scanf("%d",&a[i]);        sum=m;        dfs(0,-1,1);        printf("%d\n",sum);    }    return 0;}
原创粉丝点击