首页 > 代码库 > hdu 4004 - The Frog's Games

hdu 4004 - The Frog's Games

题目:有一些岛屿,分布在一条线上,问青蛙最少的能力是跳多远,可以不超过m次跳刀对岸。

分析:贪心,二分。已知能力的话,每次跳到最远即可,所以二分能力即可。

说明:2011大连网选题4。(2011-09-19 01:09)

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

int  Leng[ 500005 ];
int  Data[ 500005 ];
int  Queue[ 500005 ];

int cmp( const void* a, const void* b )
{
    return *((int *)a) - *((int *)b);
}

bool greedy( int n, int m, int maxdist )
{
    Queue[ 0 ] = 0;
    int move = 0,save = 1;
    while ( move < save ) {
        int now  = Queue[ move ++ ];
        int dist = 0;
        while ( now <= n && dist + Leng[ now ] <= maxdist )
            dist += Leng[ now ++ ];
        if ( now > n ) return true;
        if ( dist == 0 ) return false;
        Queue[ save ++ ] = now;
        if ( save > m ) return false;
    }
    return false;
}

int main()
{
    int L,n,m;
    while ( scanf("%d%d%d",&L,&n,&m) != EOF ) {
        for ( int i = 0 ; i < n ; ++ i )
            scanf("%d",&Data[ i ]);
        Data[ n ] = L;
        qsort( Data, n+1, sizeof( int ), cmp );
        
        Leng[ 0 ] = Data[ 0 ];
        for ( int i = 1  ; i <= n ; ++ i )
            Leng[ i ] = Data[ i ] - Data[ i-1 ];

        int low = 0;
        int hig = L;
        int mid = (low+hig)/2;    
        while ( low < hig ) {
            if ( greedy( n, m, mid ) )
                hig = mid;
            else low = mid+1;
            mid = (hig+low)/2;
        }
        
        printf("%d\n",mid);
    }
    return 0;
}

hdu 4004 - The Frog's Games