[算法 笔记] 求近似和
问题出自blog:http://blog.csdn.net/v_july_v/article/details/6803368
问题描述:有n个正实数(按照大小升序排列),另一个实数m。需要算出若干个x,使这个几个x的和与m最接近。请描述实现算法啊,并指出算法复杂度。
利用贪婪算法,从后向前仅考虑当前计算结果最接近实数m的值,时间复杂度O(n)
源代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <stdlib.h> // for srand(), rand() 3 #include <time.h> // for time() 4 5 int which_sum_is_near_number( const int *array_number, 6 const int n_len, 7 const int equal_number ) 8 { 9 int start_index = n_len - 1, 10 *array_path = NULL, 11 path_index = 0, 12 tmp_summary = 0, // 计算临时和 13 min_diff = array_number[n_len - 1]; // 计算最小差值 14 15 // 检查函数参数 16 if ( NULL == array_number || n_len <= 0 17 || equal_number <= 0 ) 18 { 19 printf( "Error for argument.\n" ); 20 return -1; 21 } 22 23 // 分配计算路径存储空间 24 array_path = (int *) calloc( n_len, sizeof(int) ); 25 if ( NULL == array_path ) 26 { 27 printf( "Out of memory.\n" ); 28 return -1; 29 } 30 31 // 计算差值 32 for ( ; start_index >= 0; --start_index ) 33 { 34 tmp_summary += array_number[start_index]; 35 36 // 若计算的临时和大于要求值或计算差值大于当前最小差值, 37 // 则排除本次计算值 38 if ( tmp_summary > equal_number 39 || ( equal_number - tmp_summary ) > min_diff ) 40 { 41 tmp_summary -= array_number[start_index]; 42 continue; 43 } 44 45 // 添加路径元素 46 array_path[path_index++] = array_number[start_index]; 47 // 更新最小差值 48 min_diff = equal_number - tmp_summary; 49 if ( tmp_summary == equal_number ) 50 { 51 break; 52 } 53 } 54 55 // 输出计算的路径值 56 printf( "\nThe elements of path is \n" ); 57 while ( --path_index >= 0 ) 58 { 59 printf( " %d", array_path[path_index] ); 60 } 61 printf( "\n" ); 62 printf( "The difference is %d.\n", min_diff ); 63 64 // 释放空间 65 free( array_path ); 66 array_path = NULL; 67 68 return min_diff; 69 } 70 71 int compare_int( const void *lhs, const void *rhs ) 72 { 73 return *(int *)lhs - *(int *)rhs; 74 } 75 76 void test_function() 77 { 78 const int array_size = 20; 79 int array_number[array_size], 80 start_index = 0, 81 equal_number = 0; 82 83 srand( (unsigned) time(0) ); 84 for ( ; start_index < array_size; ++start_index ) 85 { 86 array_number[start_index] = rand() % 100; 87 } 88 equal_number = rand() % 200; 89 90 // sorting 91 qsort( array_number, array_size, sizeof(int), compare_int ); 92 93 printf( "\nThe elements in array is \n" ); 94 for ( start_index = 0; start_index < array_size; ++start_index ) 95 printf( " %d", array_number[start_index] ); 96 printf( "\nThe number is %d.\n", equal_number ); 97 98 which_sum_is_near_number( array_number, array_size, equal_number ); 99 } 100 101 int main() 102 { 103 test_function(); 104 105 return 0; 106 }
有问题欢迎大家知道!!