HDU 1796 How many integers can you find (容斥定理 + 二进制)
2015-08-15 09:25
555 查看
How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5493 Accepted Submission(s): 1567
Problem Description
Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10},
all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0<N<2^31,0<M<=10, and the M integer are non-negative and won’t exceed 20.
Output
For each case, output the number.
Sample Input
12 2 2 3
Sample Output
7今天扣了一下容斥定理,离散结构中有,却是不记得了,总结一下,实现容斥原理大致有三种方法:dfs,队列数组,二进制,可以按照实际情况以及个人爱好自己选择容斥定理内容: 大家可以理解为奇数个的并集则是加,偶数个的并集则是减,具体的建议大家翻阅资料了解原理这道题目很明显符合容斥定理,所以我就用二进制过了#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int MAXN = 50 + 5; int n, m; LL A[MAXN]; LL gcd(LL a,LL b) { return b ? gcd(b, a % b) : a; } LL lcm(LL a,LL b) { return a / gcd(a, b) * b; } int main() { while(~ scanf("%d%d", &n, &m)) { for(int i = 0; i < m; i ++) { scanf("%I64d", &A[i]); } int ms = 0; for(int i = 0 ;i < m;i ++){ if(A[i] == 0) continue; A[ms ++] = A[i]; } m = ms; LL ans = 0; for(int i = 1; i < (1 << m); i ++) { int bits = 0; LL res = 1; for(int j = 0; j < m; j ++) { if(i & (1 << j)) { bits ++; res = lcm(res, A[j]); } } if(bits & 1) ans += (LL)(n - 1) / res; else ans -= (LL)(n - 1) / res; } printf("%I64d\n", ans); } return 0; }
相关文章推荐
- 我的博客
- 黑马程序员——集合类
- 字典树模版
- BASH
- 黑马程序员——String
- Ubuntu 有望让你安装最新 Nvidia Linux 驱动更简单
- 解决A master URL must be set in your configuration
- 【C语言经典实例】-选择排序
- 一个优秀程序员的成长之路
- SQL Server无日志恢复数据库(2种方法)
- 黑马程序员——多线程2多线程安全性的探讨
- PHP程序在引号前自动加反斜杠的原因与处理办法
- Android(java)学习笔记158:Java程序入口和Android的APK入口
- HDU 2068 RPG的错排(排列组合,错排)非常详细~
- HDU 5289-B - Assignment-贪心
- hdu 5055 Bob and math problem
- 强引用,软引用与弱引用
- android apk文件安装
- 生产汽车(单调队列+斜率优化)
- 二叉树 (Binary Tree)的遍历