首页 > 代码库 > hdu 4208 - The time of a day

hdu 4208 - The time of a day

题目:从1~n去若干个数字,使得他们的最小公倍数不小于M的有多少种。

分析:dp,数论,搜索。其实就是一个背包类似物。(貌似离散化dp写起来很简洁)

             由于每个素数因子的个数有限(不超过20个)直接打表(dfs)计算出所有的最小公倍数;

             然后DP更行最小公倍数即可;

             这个题目要做一些优化(囧,TLE一次):

             首先,二分查找,找到要更新的公倍数对应的位置;再次,就是把结果打表,然后每次求和即可。

说明:在比赛进行了2:30小时之后,我们终于A掉了第一道题,随即我终于找到了这个题的bug并将它A了;

             原来是二分的上界 写成了36863.。。囧少写了一个WA半天。(2011-09-19 01:02)。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

long long Lcm[ 42 ];
long long Pri[ 12 ] = {2,3,5,7,11,13,17,19,23,29,31,37};
long long Num[ 12 ] = {5,3,2,1,1,1,1,1,1,1,1,1};
long long Sav[ 36880 ];
long long Count = 0;
long long F[ 42 ][ 36880 ];

long long gcd( long long a, long long b )
{
    return a%b?gcd( b, a%b ):b;
}

long long lcm( long long a, long long b )
{
    return a/gcd( a, b )*b;
}

void dfs( int s, long long v )
{
    if ( s == 12 ) Sav[ Count ++ ] = v;
    else 
    for ( int i = 0 ; i <= Num[ s ] ; ++ i ) {
        long long save = 1LL;
        for ( int j = 0 ; j < i ; ++ j )
            save *= Pri[ s ];
        dfs( s+1, v*save );
    }
}

int cmp( const void* a, const void* b )
{
    long long *p = (long long *)a;
    long long *q = (long long *)b;
    if ( *p < *q ) return -1;
    else return 1;
}

int search( long long V )
{
    int m,l = 1,h = 36864;
    while ( l < h ) {
        m = (l+h+1)>>1;
        if ( Sav[ m ] > V )
            h = m-1;
        else l = m;
    }
    return h;
}

int main()
{
    Lcm[ 1 ] = 1;
    for ( int i = 2 ; i <= 40 ; ++ i )
        Lcm[ i ] = lcm( Lcm[ i-1 ], i );
    Count = 0LL;
    dfs( 0, 1LL );
    qsort( Sav, Count+1, sizeof( long long ), cmp );
    
    for ( int i = 1 ; i <= 40 ; ++ i )
    for ( int j = 0 ; j <= Count ; ++ j )
        F[ i ][ j ] = 0LL;
        
    for ( int i = 1 ; i <= 40 ; ++ i ) {
        for ( int j = 1 ; j <= Count ; ++ j )
            F[ i ][ j ] = F[ i-1 ][ j ];
        for ( int j = 1 ; j <= Count ; ++ j )
            F[ i ][ search( lcm( Sav[ j ], i ) ) ] += F[ i-1 ][ j ];
        F[ i ][ i ] += 1LL;
    }
    
    long long T,N,M;
    while ( ~scanf("%I64d",&T) )
    for ( int t = 1 ; t <= T ; ++ t ) {
        scanf("%I64d%I64d",&N,&M);
        int V = search( Lcm[ N ] );
                
        long long sum = 0LL;
        for ( int i = 1 ; i <= V ; ++ i )
            if ( Sav[ i ] >= M )
                sum += F[ N ][ i ];
        
        printf("Case #%d: %I64d\n",t,sum);
    }
    return 0;
}

hdu 4208 - The time of a day