第十四周训练总结(二)

来源:互联网 发布:淘宝店标 编辑:程序博客网 时间:2024/05/22 17:34

这几天重点看了一下容斥原理。容斥原理,在高中学过一点,但是用来解题的话,还是有障碍,特别是不知道怎么写代码。

容斥原理的想法就是求多个集合的并集.所以要先设计好集合组合数学问题中,正面解决会困难,常用方法是正难则反,使用容斥原理求反向在用全集减去.将对立面的限制条件分析清楚例如求区间互质的数的个数,则用除法等计算出一个数的倍数的方法再减去

容斥原理的常见代码写法DFS法

模板:
  1. #include<iostream>  
  2. #include<algorithm>  
  3. #include<cstdio>   
  4. #include<iomanip>  
  5. using namespace std;  
  6. #define out(x) cout<<#x<<": "<<x<<endl  
  7. const double eps(1e-8);  
  8. const int maxn=10100;  
  9. const long long maxint=-1u>>1;  
  10. const long long maxlong=maxint*maxint;  
  11. typedef long long lint;  
  12. int n;  
  13. double p[maxn],ans;  
  14.   
  15. void init()  
  16. {  
  17.     for (int i=1; i<=n; i++)  
  18.         cin>>p[i];  
  19. }  
  20.   
  21. void dfs(int x, int tot, double sum)  
  22. {  
  23.     if (x==n+1)  
  24.     {  
  25.         if (sum==0.0) return;//divide by zero is illegal  
  26.         if (tot&1)  
  27.             ans+=1/sum;  
  28.         else  
  29.             ans-=1/sum;  
  30.         return;  
  31.     }  
  32.     dfs(x+1,tot,sum);  
  33.     dfs(x+1,tot+1,sum+p[x]);  
  34. }      
  35.   
  36. void work()  
  37. {  
  38.     ans=0;  
  39.     dfs(1,0,0.0);  
  40.     printf("%.4f\n",ans);  
  41. }  
  42.   
  43. int main()  
  44. {  
  45.     while(cin>>n)  
  46.     {  
  47.     init();  
  48.     work();  
  49.     }  
  50.     return 0;  
  51. }  



原创粉丝点击