HDU - 1796 How many integers can you find(容斥原理)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 1796 How many integers can you find(容斥原理)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出一個n,再給出一個含有m個數(shù)的集合,問1~n-1中有多少個數(shù)可以被集合中的所有數(shù)字整除
題目分析:因?yàn)?~n-1中的每個數(shù)可能會被整除多次,所以我們可以利用容斥原理枚舉集合,奇加偶減,從而就能算出正確的答案了,類似于之前計算有多少種互斥的數(shù)那樣寫一個dfs就好,不過需要修改一個細(xì)節(jié),就是累乘的地方要寫成求lcm,因?yàn)橐粋€數(shù)若想被集合中的所有數(shù)整除,只需要被其lcm整除就夠了,再就是這個題目中會出現(xiàn)0,輸入時預(yù)處理將0去掉就好了,最后就是記得開longlong,計算的過程中可能會爆int
代碼:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;LL n,ans;int m,tot,a[N];void dfs(int step,int cnt,LL sum) {if(step==tot+1){if(cnt){if(cnt&1)ans+=n/sum;elseans-=n/sum;}return;}dfs(step+1,cnt,sum);dfs(step+1,cnt+1,sum*a[step]/__gcd(sum,(LL)a[step])); }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);while(scanf("%lld%d",&n,&m)!=EOF){ans=0;n--;tot=0;for(int i=1;i<=m;i++){int val;scanf("%d",&val);if(val)a[++tot]=val;}dfs(1,0,1);printf("%lld\n",ans);}return 0; }?
超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的HDU - 1796 How many integers can you find(容斥原理)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 - P2754 [CTSC1999
- 下一篇: UVA - 11806 Cheerlea