hdu 1796 容斥原理(dfs)
很基本的容斥原理的题目,注意要先把0去掉。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 6 typedef long long ll; 7 const int N = 10; 8 int s[N]; 9 bool visit[N]; 10 int n, m, ans; 11 12 ll gcd( ll x, ll y ) 13 { 14 return y ? gcd( y, x % y ) : x; 15 } 16 17 ll lcm( ll x, ll y ) 18 { 19 return x / gcd( x, y ) * y; 20 } 21 22 void dfs( int cur ) 23 { 24 if ( cur == m ) 25 { 26 int cnt = 0, r = 1; 27 ll d = 1; 28 for ( int i = 0; i < m; i++ ) 29 { 30 if ( visit[i] ) 31 { 32 d = lcm( d, s[i] ); 33 cnt++; 34 } 35 } 36 if ( cnt == 0 ) return ; 37 if ( cnt % 2 == 0 ) r = -1; 38 ans += n / d * r; 39 return ; 40 } 41 visit[cur] = 0; 42 dfs( cur + 1 ); 43 visit[cur] = 1; 44 dfs( cur + 1 ); 45 return ; 46 } 47 48 int main () 49 { 50 while ( scanf("%d%d", &n, &m) != EOF ) 51 { 52 int tn = 0; 53 for ( int i = 0; i < m; i++ ) 54 { 55 int tmp; 56 scanf("%d", &tmp); 57 if ( tmp != 0 ) 58 { 59 s[tn++] = tmp; 60 } 61 } 62 m = tn; 63 ans = 0; 64 n--; 65 dfs(0); 66 printf("%d\n", ans); 67 } 68 return 0; 69 }