#include <stdio.h> int N_site[ 50001 ] ; void swap( int *a , int *b ){ int tmp = *a ; *a = *b ; *b = tmp ; } void sot ( int N ) { for ( int i = 0 ; i < N ; i ++ ) for ( int j = i ; j >= 0 ; j-- ) if ( N_site[ j ] < N_site[ j - 1 ] ) swap ( &N_site[ j ] , &N_site[ j - 1 ] ) ; } int try_1 ( int R , int N , int K ) { int num = 0 ; int site ; for ( int i = 0 ; i < N ; ){ site = N_site[ i ] + R ; num += 1 ; if ( num > K ) return 0 ; if ( N_site[ N - 1 ] <= site ) return 1 ; while( N_site[ i ] <= site ) i++ ; } } int main() { int R , N , K ; while( scanf( "%d %d" , &N , &K ) != EOF ){ for ( int i = 0 ; i < N ; i++ ) scanf( "%d" , &N_site[ i ] ) ; sot( N ) ; R = N_site[ N - 1 ] - N_site[ 0 ] ; while ( try_1( R - 1 , N , K ) ) R-- ; printf ( "%d\n" , R ) ; } return 0 ; }
#include int N_site[ 50001 ] ; void swap( int *a , int *b ){ int tmp = *a ; *a = *b ; *b = tmp ; } void sot ( int N ) { for ( int i = 0 ; i < N ; i ++ ) for ( int j = i ; j >= 0 ; j-- ) if ( N_site[ j ] < N_site[ j - 1 ] ) swap ( &N_site[ j ] , &N_site[ j - 1 ] ) ; } int try_1 ( int R , int N , int K ) { int num = 0 ; int site ; for ( int i = 0 ; i < N ; ){ site = N_site[ i ] + R ; num += 1 ; if ( num > K ) return 0 ; if ( N_site[ N - 1 ] <= site ) return 1 ; while( N_site[ i ] <= site ) i++ ; } } int main() { int R , N , K ; while( scanf( "%d %d" , &N , &K ) != EOF ){ for ( int i = 0 ; i < N ; i++ ) scanf( "%d" , &N_site[ i ] ) ; sot( N ) ; R = N_site[ N - 1 ] - N_site[ 0 ] ; while ( try_1( R - 1 , N , K ) ) R-- ; printf ( "%d\n" , R ) ; } return 0 ; }
排序建議不要用bubble_sort,效率太差,要改用如merge_sort會內建等複雜度O(nlogn)的演算法