1. 程式人生 > >HDU 1796 How many integers can you find 【容斥】

HDU 1796 How many integers can you find 【容斥】

stream 題目 size get tdi pri cst namespace main

<題目鏈接>

題目大意:

給你m個數,其中可能含有0,問有多少小於n的正數能整除這個m個數中的某一個。

解題分析:

容斥水題,直接對這m個數(除0以外)及其組合的倍數在[1,n)中的個數即可,因為可能會重復計算,所以在疊加的時候進行容斥處理,下面用的是位運算實現容斥。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 typedef long
long ll; 8 ll n,m,arr[15]; 9 ll gcd(ll a,ll b){ 10 return b==0?a:gcd(b,a%b); 11 } 12 ll lcm(ll a,ll b){ 13 return a*b/gcd(a,b); 14 } 15 int main(){ 16 while(cin>>n>>m){ 17 int cnt=0; 18 for(int i=1;i<=m;i++){ 19 scanf("%lld",&arr[cnt]);
20 if(arr[cnt])cnt++; 21 } 22 ll sum=0; 23 for(int i=1;i<(1<<cnt);i++){ 24 ll res=1,tot=0; 25 for(int j=0;j<cnt;j++){ 26 if(i & (1<<j)){ 27 res=lcm(res,arr[j]); //註意這裏將不同的數組合時,是求它們的lcm,而不是直接相乘
28 tot++; //組合的數個數,用於後面判奇偶 29 } 30 } 31 if(tot & 1)sum+=(n-1)/res; //題意不包含n 32 else sum-=(n-1)/res; 33 } 34 printf("%lld\n",sum); 35 } 36 }

2019-02-09

HDU 1796 How many integers can you find 【容斥】