HDOJ1796 How many integers can you find(dfs+容斥)
阿新 • • 發佈:2017-06-07
article nor man small 接下來 long long line cas example
Total Submission(s): 6048 Accepted Submission(s): 1735
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
Sample Output
How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6048 Accepted Submission(s): 1735
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
題目鏈接:點擊打開鏈接
給出n, m, n代表1 - n的一個序列, 接下來m個數組成的集合, 問序列中能夠整除任一集合中的一個數的個數和為多少.
對讀入的m個數進行推斷, 非0則賦值到a數組中, 進行dfs, dfs時進行容斥運算, id為奇數則加, 為偶數則減去反復的.
AC代碼:
#include "iostream" #include "cstdio" #include "cstring" #include "algorithm" #include "queue" #include "stack" #include "cmath" #include "utility" #include "map" #include "set" #include "vector" #include "list" #include "string" using namespace std; typedef long long ll; const int MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; const int MAXN = 15; int n, m, num, ans, a[MAXN]; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } void dfs(int cur, int lcm, int id) { lcm = a[cur] / gcd(a[cur], lcm) * lcm; if(id & 1) ans += (n - 1) / lcm; else ans -= (n - 1) / lcm; for(int i = cur + 1; i < num; ++i) dfs(i, lcm, id + 1); } int main(int argc, char const *argv[]) { while(scanf("%d%d", &n, &m) != EOF) { num = ans = 0; while(m--) { int x; scanf("%d", &x); if(x != 0) a[num++] = x; } for(int i = 0; i < num; ++i) dfs(i, a[i], 1); printf("%d\n", ans); } return 0; }
HDOJ1796 How many integers can you find(dfs+容斥)