HDU - 1796 How many integers can you find(容斥原理)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 1796 How many integers can you find(容斥原理)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個n,再給出一個含有m個數的集合,問1~n-1中有多少個數可以被集合中的所有數字整除
題目分析:因為1~n-1中的每個數可能會被整除多次,所以我們可以利用容斥原理枚舉集合,奇加偶減,從而就能算出正確的答案了,類似于之前計算有多少種互斥的數那樣寫一個dfs就好,不過需要修改一個細節,就是累乘的地方要寫成求lcm,因為一個數若想被集合中的所有數整除,只需要被其lcm整除就夠了,再就是這個題目中會出現0,輸入時預處理將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; }?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的HDU - 1796 How many integers can you find(容斥原理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 - P2754 [CTSC1999
- 下一篇: UVA - 11806 Cheerlea