这是一道相对简单的优化问题,建立目标函数Salary_max,约束条件为Si、Ni和Pi。不追求运行速度的话就采用遍历法;否则采用点计算智能的方法。
梦想拥有一台龙芯3A-4000
#include <stdio.h> #define MAX_GROUP 1000 #define MAX_BOOK 2000 int i; int res[MAX_GROUP], res_count = 0; int max_sum; int found; int wage, n, p[MAX_BOOK + 1], sel[MAX_BOOK + 1]; void input_and_sort_data() { int i, j, m, t; for ( i = 1; i <= n; i++ ) { printf ( "输入第 %d 本书的价格:", i ); scanf( "%d", &p[i] ); } for ( i = 1; i < n; i++ ) { m = i; for ( j = i + 1; j <= n; j++ ) { if ( p[m] > p[j] ) m = j; } t = p[m]; p[m] = p[i]; p[i] = t; } } void book_try( int k, int sum ) { int i; if ( sum == wage ) { max_sum = sum; found = 1; return; } else if ( sum > max_sum ) { max_sum = sum; } for ( i = sel[k] + 1; i <= n; i++ ) { sel[k + 1] = i; if ( sum + p[sel[k + 1]] <= wage ) { book_try( k + 1, sum + p[sel[k + 1]] ); if ( found ) return; } else { return; } } } int main( void ) { p[0] = sel[0] = 0; while ( 1 ) { printf ( "输入工资:" ); if ( scanf( "%d", &wage ) == EOF ) break; printf ( "输入书的种类:" ); scanf( "%d", &n ); input_and_sort_data(); max_sum = 0; found = 0; book_try( 0, 0 ); res[res_count++] = max_sum; } printf ( "\n" ); for ( i = 0; i < res_count; i++ ) printf ( "%d\n", res[i] ); return 0; }